From f6698b5d2c54c7db6d74dc8496459e0f371ca8b4 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 13 Jun 2023 22:13:55 +0000 Subject: [PATCH 1/4] feat: added RPCs StopAirflowCommand, ExecuteAirflowCommand, PollAirflowCommand, DatabaseFailover, FetchDatabaseProperties PiperOrigin-RevId: 540051332 Source-Link: https://github.com/googleapis/googleapis/commit/b84c697241488e5dd521b09b7eaf75b081648585 Source-Link: https://github.com/googleapis/googleapis-gen/commit/02564778c80b7b5dc2ddff413be253ef24b69165 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW9yY2hlc3RyYXRpb24tYWlyZmxvdy8uT3dsQm90LnlhbWwiLCJoIjoiMDI1NjQ3NzhjODBiN2I1ZGMyZGRmZjQxM2JlMjUzZWYyNGI2OTE2NSJ9 --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../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 | 115 + .../airflow/service/gapic_version.py | 16 + .../orchestration/airflow/service/py.typed | 2 + .../airflow/service_v1/__init__.py | 116 + .../airflow/service_v1/gapic_metadata.json | 242 + .../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 | 1739 +++++ .../services/environments/client.py | 1951 ++++++ .../services/environments/pagers.py | 139 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 337 + .../services/environments/transports/grpc.py | 631 ++ .../environments/transports/grpc_asyncio.py | 630 ++ .../services/environments/transports/rest.py | 1803 +++++ .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 464 ++ .../services/image_versions/client.py | 660 ++ .../services/image_versions/pagers.py | 139 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 176 + .../image_versions/transports/grpc.py | 319 + .../image_versions/transports/grpc_asyncio.py | 318 + .../image_versions/transports/rest.py | 534 ++ .../airflow/service_v1/types/__init__.py | 108 + .../airflow/service_v1/types/environments.py | 2171 ++++++ .../service_v1/types/image_versions.py | 148 + .../airflow/service_v1/types/operations.py | 147 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 184 + ...d_environments_create_environment_async.py | 55 + ...ed_environments_create_environment_sync.py | 55 + ...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 + ...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 + ...ed_environments_list_environments_async.py | 52 + ...ted_environments_list_environments_sync.py | 52 + ...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 + ...mage_versions_list_image_versions_async.py | 52 + ...image_versions_list_image_versions_sync.py | 52 + ...loud.orchestration.airflow.service.v1.json | 2076 ++++++ .../v1/scripts/fixup_service_v1_keywords.py | 188 + .../v1/setup.py | 90 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.7.txt | 9 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../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 | 5935 +++++++++++++++++ .../gapic/service_v1/test_image_versions.py | 2361 +++++++ .../v1beta1/.coveragerc | 13 + .../v1beta1/.flake8 | 33 + .../v1beta1/MANIFEST.in | 2 + .../v1beta1/README.rst | 49 + .../v1beta1/docs/conf.py | 376 ++ .../v1beta1/docs/index.rst | 7 + .../docs/service_v1beta1/environments.rst | 10 + .../docs/service_v1beta1/image_versions.rst | 10 + .../v1beta1/docs/service_v1beta1/services.rst | 7 + .../v1beta1/docs/service_v1beta1/types.rst | 6 + .../orchestration/airflow/service/__init__.py | 105 + .../airflow/service/gapic_version.py | 16 + .../orchestration/airflow/service/py.typed | 2 + .../airflow/service_v1beta1/__init__.py | 106 + .../service_v1beta1/gapic_metadata.json | 197 + .../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 | 1552 +++++ .../services/environments/client.py | 1761 +++++ .../services/environments/pagers.py | 139 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 295 + .../services/environments/transports/grpc.py | 555 ++ .../environments/transports/grpc_asyncio.py | 554 ++ .../services/environments/transports/rest.py | 1470 ++++ .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 464 ++ .../services/image_versions/client.py | 660 ++ .../services/image_versions/pagers.py | 139 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 176 + .../image_versions/transports/grpc.py | 319 + .../image_versions/transports/grpc_asyncio.py | 318 + .../image_versions/transports/rest.py | 534 ++ .../airflow/service_v1beta1/types/__init__.py | 98 + .../service_v1beta1/types/environments.py | 2096 ++++++ .../service_v1beta1/types/image_versions.py | 148 + .../service_v1beta1/types/operations.py | 138 + .../v1beta1/mypy.ini | 3 + .../v1beta1/noxfile.py | 184 + ...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 + ...d_environments_delete_environment_async.py | 55 + ...ed_environments_delete_environment_sync.py | 55 + ...ated_environments_get_environment_async.py | 51 + ...rated_environments_get_environment_sync.py | 51 + ...ed_environments_list_environments_async.py | 52 + ...ted_environments_list_environments_sync.py | 52 + ...erated_environments_load_snapshot_async.py | 55 + ...nerated_environments_load_snapshot_sync.py | 55 + ...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 + ...d_environments_update_environment_async.py | 55 + ...ed_environments_update_environment_sync.py | 55 + ...mage_versions_list_image_versions_async.py | 52 + ...image_versions_list_image_versions_sync.py | 52 + ...orchestration.airflow.service.v1beta1.json | 1617 +++++ .../scripts/fixup_service_v1beta1_keywords.py | 185 + .../v1beta1/setup.py | 90 + .../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 | 9 + .../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 | 5117 ++++++++++++++ .../service_v1beta1/test_image_versions.py | 2361 +++++++ 160 files changed, 49139 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/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_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_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_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_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_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/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_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_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_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_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_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_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_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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py new file mode 100644 index 000000000000..55eb11f096a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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"2022, 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 = None + +# 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..511c9ad31561 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CreateEnvironmentRequest +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 DeleteEnvironmentRequest +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 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 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 UpdateEnvironmentRequest +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', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'UpdateEnvironmentRequest', + '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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..366523066689 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CreateEnvironmentRequest +from .types.environments import DatabaseConfig +from .types.environments import DatabaseFailoverRequest +from .types.environments import DatabaseFailoverResponse +from .types.environments import DeleteEnvironmentRequest +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 IPAllocationPolicy +from .types.environments import ListEnvironmentsRequest +from .types.environments import ListEnvironmentsResponse +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 UpdateEnvironmentRequest +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', +'CreateEnvironmentRequest', +'DatabaseConfig', +'DatabaseFailoverRequest', +'DatabaseFailoverResponse', +'DeleteEnvironmentRequest', +'EncryptionConfig', +'Environment', +'EnvironmentConfig', +'EnvironmentsClient', +'ExecuteAirflowCommandRequest', +'ExecuteAirflowCommandResponse', +'FetchDatabasePropertiesRequest', +'FetchDatabasePropertiesResponse', +'GetEnvironmentRequest', +'IPAllocationPolicy', +'ImageVersion', +'ImageVersionsClient', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListImageVersionsRequest', +'ListImageVersionsResponse', +'LoadSnapshotRequest', +'LoadSnapshotResponse', +'MaintenanceWindow', +'MasterAuthorizedNetworksConfig', +'NetworkingConfig', +'NodeConfig', +'OperationMetadata', +'PollAirflowCommandRequest', +'PollAirflowCommandResponse', +'PrivateClusterConfig', +'PrivateEnvironmentConfig', +'RecoveryConfig', +'SaveSnapshotRequest', +'SaveSnapshotResponse', +'ScheduledSnapshotsConfig', +'SoftwareConfig', +'StopAirflowCommandRequest', +'StopAirflowCommandResponse', +'UpdateEnvironmentRequest', +'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..e35a8b09bf99 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json @@ -0,0 +1,242 @@ + { + "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" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..e8e1c3845db5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..63bae46eaf47 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..4b37a1ba9e0b --- /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,1739 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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 + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 + + get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_environments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.StopAirflowCommandRequest(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.stop_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.PollAirflowCommandRequest(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.poll_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.SaveSnapshotRequest(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.save_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.LoadSnapshotRequest(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.load_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.DatabaseFailoverRequest(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.database_failover, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, + 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(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..09cc5463bf16 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py @@ -0,0 +1,1951 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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 common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.ListEnvironmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.ExecuteAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.StopAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.PollAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.SaveSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.LoadSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.DatabaseFailoverRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.FetchDatabasePropertiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..61dda03258a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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) 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..9384fe0b2c46 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..51d0225f04d6 --- /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,337 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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.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 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..48ad6fda5f55 --- /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,631 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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 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..14cc807c075d --- /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,630 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.orchestration.airflow.service_v1.types import environments +from google.longrunning import operations_pb2 +from google.longrunning import operations_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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def 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 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 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..76cdeabf2fbf --- /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,1803 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1.types import environments +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_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_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_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_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 + + 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_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_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_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_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_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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_environment(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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_environment(resp) + return resp + + 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_environment(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 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 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 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 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 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..c8beb58456d9 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..331abbfbda40 --- /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,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.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 +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 + + DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + + 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 + + get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_image_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..5883379867ba --- /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,660 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # 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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageVersionsTransport): + # transport is a ImageVersionsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_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.') + + # Minor optimization to avoid making a copy if the user passes + # in a image_versions.ListImageVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..328e922af2cb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..a11e27f277bb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..8511a3e8d148 --- /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,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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..fafc0ffbf30f --- /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,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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..52c70b26d13d --- /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,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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 +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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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 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..06cb8c005fc8 --- /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,534 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1.types import image_versions + +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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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..2fdc02aaa78b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + CreateEnvironmentRequest, + DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, + DeleteEnvironmentRequest, + EncryptionConfig, + Environment, + EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, + GetEnvironmentRequest, + IPAllocationPolicy, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + LoadSnapshotRequest, + LoadSnapshotResponse, + MaintenanceWindow, + MasterAuthorizedNetworksConfig, + NetworkingConfig, + NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, + PrivateClusterConfig, + PrivateEnvironmentConfig, + RecoveryConfig, + SaveSnapshotRequest, + SaveSnapshotResponse, + ScheduledSnapshotsConfig, + SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, + UpdateEnvironmentRequest, + WebServerConfig, + WebServerNetworkAccessControl, + WorkloadsConfig, +) +from .image_versions import ( + ImageVersion, + ListImageVersionsRequest, + ListImageVersionsResponse, +) +from .operations import ( + OperationMetadata, +) + +__all__ = ( + 'CheckUpgradeResponse', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'UpdateEnvironmentRequest', + '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..30ee1fcd3a68 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py @@ -0,0 +1,2171 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'EnvironmentConfig', + 'WebServerNetworkAccessControl', + 'DatabaseConfig', + 'WebServerConfig', + 'EncryptionConfig', + 'MaintenanceWindow', + 'SoftwareConfig', + 'IPAllocationPolicy', + 'NodeConfig', + 'PrivateClusterConfig', + 'NetworkingConfig', + 'PrivateEnvironmentConfig', + 'WorkloadsConfig', + 'RecoveryConfig', + 'ScheduledSnapshotsConfig', + 'MasterAuthorizedNetworksConfig', + 'Environment', + '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_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 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_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. + """ + 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, + ) + + +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-*.*.*. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + + +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.*.*. + """ + + 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, + ) + + +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 + """ + + 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, + ) + + +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-*.*.*. + 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, + ) + 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. + """ + + 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, + ) + + 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, + ) + + +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 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. + """ + 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, + ) + + +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, + ) + + +__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..2bb874963b6c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..eefba0b0dc1c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..48efa670881b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/orchestration/airflow/service_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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..d0655bf2a8d1 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e0a9c90c110b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..8c36632bb46f --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6b3c921a3abd --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..ea715af765ad --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7563eeb487ad --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..19be15194623 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..cd333c7a0c19 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0de483668671 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..351c665a2dab --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a2534c3f26bb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..666b75a8df6a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..150ae0c0281a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0724fdb3ee19 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..953a0294dff3 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9d3283833652 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a9943af88b29 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..de3a51afdf0b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c580bdd3f5c2 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..09882bf17a2a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..126036b5031c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..b7939eb741bc --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a0cbc7e8484f --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..902831c1966c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..84fb0d50f83d --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7d5b6624afd5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..73f9b69284b1 --- /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,2076 @@ +{ + "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.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.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.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.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.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..a5e0a38cc890 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py @@ -0,0 +1,188 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', ), + 'database_failover': ('environment', ), + 'delete_environment': ('name', ), + 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), + 'fetch_database_properties': ('environment', ), + 'get_environment': ('name', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), + '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', ), + } + + 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..23b72c183665 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-orchestration-airflow' + + +description = "Google Cloud Orchestration Airflow API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/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..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..8741e5d4da57 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py @@ -0,0 +1,5935 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.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 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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 + + +@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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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, + ) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +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: + 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(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, + )) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +@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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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: + 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(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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch + 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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + # 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] + assert args[0] == environments.StopAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.StopAirflowCommandRequest() + + # 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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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.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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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: + 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(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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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: + 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(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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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" + + +@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 + pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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'] + + +@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 + pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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.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" + + +@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" + + +@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" + + +@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 + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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_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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).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 + + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() + 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', + '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.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_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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"): + 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"): + 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"): + 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, + 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..b63c0fe80da3 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py @@ -0,0 +1,2361 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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 +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 + + +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 + + +@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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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: + 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(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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch + 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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() + 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"): + 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"): + 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"): + 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, + 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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py new file mode 100644 index 000000000000..0de401396097 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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"2022, 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 = None + +# 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..0dc5c64403b5 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 DatabaseConfig +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteEnvironmentRequest +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 ExecuteAirflowCommandResponse +from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetEnvironmentRequest +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 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 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 UpdateEnvironmentRequest +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', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'RestartWebServerRequest', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'UpdateEnvironmentRequest', + '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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..287fce0f4d42 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CheckUpgradeRequest +from .types.environments import CheckUpgradeResponse +from .types.environments import CloudDataLineageIntegration +from .types.environments import CreateEnvironmentRequest +from .types.environments import DatabaseConfig +from .types.environments import DeleteEnvironmentRequest +from .types.environments import EncryptionConfig +from .types.environments import Environment +from .types.environments import EnvironmentConfig +from .types.environments import ExecuteAirflowCommandResponse +from .types.environments import GetEnvironmentRequest +from .types.environments import IPAllocationPolicy +from .types.environments import ListEnvironmentsRequest +from .types.environments import ListEnvironmentsResponse +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 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 UpdateEnvironmentRequest +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', +'CheckUpgradeRequest', +'CheckUpgradeResponse', +'CloudDataLineageIntegration', +'CreateEnvironmentRequest', +'DatabaseConfig', +'DeleteEnvironmentRequest', +'EncryptionConfig', +'Environment', +'EnvironmentConfig', +'EnvironmentsClient', +'ExecuteAirflowCommandResponse', +'GetEnvironmentRequest', +'IPAllocationPolicy', +'ImageVersion', +'ImageVersionsClient', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListImageVersionsRequest', +'ListImageVersionsResponse', +'LoadSnapshotRequest', +'LoadSnapshotResponse', +'MaintenanceWindow', +'MasterAuthorizedNetworksConfig', +'NetworkingConfig', +'NodeConfig', +'OperationMetadata', +'PollAirflowCommandResponse', +'PrivateClusterConfig', +'PrivateEnvironmentConfig', +'RecoveryConfig', +'RestartWebServerRequest', +'SaveSnapshotRequest', +'SaveSnapshotResponse', +'ScheduledSnapshotsConfig', +'SoftwareConfig', +'UpdateEnvironmentRequest', +'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..1f120bab3d17 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json @@ -0,0 +1,197 @@ + { + "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" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "RestartWebServer": { + "methods": [ + "restart_web_server" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "RestartWebServer": { + "methods": [ + "restart_web_server" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "RestartWebServer": { + "methods": [ + "restart_web_server" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..e8e1c3845db5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..63bae46eaf47 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..cc89042165e1 --- /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,1552 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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 + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 + + get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_environments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.RestartWebServerRequest(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.restart_web_server, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.CheckUpgradeRequest(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.check_upgrade, + 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(( + ("environment", request.environment), + )), + ) + + # 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 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.SaveSnapshotRequest(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.save_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.LoadSnapshotRequest(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.load_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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 list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..1d81c379c6b6 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py @@ -0,0 +1,1761 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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 common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.ListEnvironmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.RestartWebServerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.CheckUpgradeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.SaveSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.LoadSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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 __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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..1c973713f7ad --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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) 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..9384fe0b2c46 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..3b1d4682c315 --- /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,295 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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.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, + ), + } + + 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 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 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..6ed6d4b6e463 --- /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,555 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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 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'] + + 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..a25c2c24a016 --- /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,554 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +from google.longrunning import operations_pb2 +from google.longrunning import operations_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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def 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 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'] + + 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..0993f1d61b9b --- /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,1470 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +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_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_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_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_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_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_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 + + 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_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_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_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_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_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_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_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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_environment(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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_environment(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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_load_snapshot(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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_save_snapshot(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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_environment(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 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 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 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 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 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 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 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..c8beb58456d9 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..3374d08e134f --- /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,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.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 +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 + + DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + + 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 + + get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_image_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..2f3b5a6f46a3 --- /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,660 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # 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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageVersionsTransport): + # transport is a ImageVersionsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_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.') + + # Minor optimization to avoid making a copy if the user passes + # in a image_versions.ListImageVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..3ae9fe2c0711 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..a11e27f277bb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..736c36ad0f7b --- /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,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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..69f0488c287a --- /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,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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..3028a9bc9c05 --- /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,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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 +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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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 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..57c90e2340b2 --- /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,534 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions + +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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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..129e57b84ac1 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py @@ -0,0 +1,98 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ( + CheckUpgradeRequest, + CheckUpgradeResponse, + CloudDataLineageIntegration, + CreateEnvironmentRequest, + DatabaseConfig, + DeleteEnvironmentRequest, + EncryptionConfig, + Environment, + EnvironmentConfig, + ExecuteAirflowCommandResponse, + GetEnvironmentRequest, + IPAllocationPolicy, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + LoadSnapshotRequest, + LoadSnapshotResponse, + MaintenanceWindow, + MasterAuthorizedNetworksConfig, + NetworkingConfig, + NodeConfig, + PollAirflowCommandResponse, + PrivateClusterConfig, + PrivateEnvironmentConfig, + RecoveryConfig, + RestartWebServerRequest, + SaveSnapshotRequest, + SaveSnapshotResponse, + ScheduledSnapshotsConfig, + SoftwareConfig, + UpdateEnvironmentRequest, + WebServerConfig, + WebServerNetworkAccessControl, + WorkloadsConfig, +) +from .image_versions import ( + ImageVersion, + ListImageVersionsRequest, + ListImageVersionsResponse, +) +from .operations import ( + OperationMetadata, +) + +__all__ = ( + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'RestartWebServerRequest', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'UpdateEnvironmentRequest', + '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..173ba73c4088 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py @@ -0,0 +1,2096 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', + 'ExecuteAirflowCommandResponse', + 'PollAirflowCommandResponse', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'EnvironmentConfig', + 'WebServerNetworkAccessControl', + 'SoftwareConfig', + 'IPAllocationPolicy', + 'NodeConfig', + 'PrivateClusterConfig', + 'NetworkingConfig', + 'PrivateEnvironmentConfig', + 'DatabaseConfig', + 'WebServerConfig', + 'EncryptionConfig', + 'MaintenanceWindow', + 'WorkloadsConfig', + '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 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 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 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 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, Cloud Composer + components may be subject to maintenance at any + time. + 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. + """ + 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 + + 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', + ) + + +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. + """ + + 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', + ) + + +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 + """ + + 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, + ) + + +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-*.*.*. + 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, + ) + 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-*.*.*. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + + +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. + """ + + 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, + ) + + 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, + ) + + +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. + """ + 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, + ) + + +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..df8c10475773 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..5acd9b0e66ef --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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. + """ + TYPE_UNSPECIFIED = 0 + CREATE = 1 + DELETE = 2 + UPDATE = 3 + CHECK = 4 + SAVE_SNAPSHOT = 5 + LOAD_SNAPSHOT = 6 + + 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..f2e63423782c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/orchestration/airflow/service_v1beta1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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..6f832b6fe4fa --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..25de62db95cb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..4e1a6142eb1c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..47af308b6b91 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..e0b793c36621 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c89c8ed4e75a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..bf32e05c79fc --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6472177609b7 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..1ab6ce68e4c3 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..56d6f268d9fb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..9a689ea86069 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6424bbd4ba94 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..2c26cfbc4c2b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..cd5f25d19a97 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e007dcd0595a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..88e01f01d51c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..a848381a9c06 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0de210f8e6d5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..3651597681c2 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0b68eee82db0 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..5ba2ed3abc15 --- /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,1617 @@ +{ + "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.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.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.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.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.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.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.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..a4ae0cb0021e --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py @@ -0,0 +1,185 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', ), + 'delete_environment': ('name', ), + 'get_environment': ('name', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), + 'load_snapshot': ('environment', 'snapshot_path', 'skip_pypi_packages_installation', 'skip_environment_variables_setting', 'skip_airflow_overrides_setting', 'skip_gcs_data_copying', ), + 'restart_web_server': ('name', ), + 'save_snapshot': ('environment', 'snapshot_location', ), + 'update_environment': ('update_mask', 'name', 'environment', ), + } + + 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..050167f108da --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-orchestration-airflow-service' + + +description = "Google Cloud Orchestration Airflow Service API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/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..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..ee0691456267 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py @@ -0,0 +1,5117 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.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 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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 + + +@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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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, + ) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +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: + 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(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, + )) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +@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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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: + 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(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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch + 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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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] + assert args[0] == environments.RestartWebServerRequest() + + # 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: + 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(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] + assert args[0] == environments.RestartWebServerRequest() + + # 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] + assert args[0] == environments.CheckUpgradeRequest() + + # 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: + 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(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] + assert args[0] == environments.CheckUpgradeRequest() + + # 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.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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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.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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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" + + +@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" + + +@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" + + +@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.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" + + +@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" + + +@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' + ) + + +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 = mock.Mock() + 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', + 'save_snapshot', + 'load_snapshot', + '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.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 +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_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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"): + 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"): + 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"): + 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, + 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..f6d496ae6a70 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py @@ -0,0 +1,2361 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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 +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 + + +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 + + +@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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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: + 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(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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch + 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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() + 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"): + 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"): + 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"): + 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, + 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 a73db217d180b815e876a3479bad94e4538f79bc Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 13 Jun 2023 22:15:45 +0000 Subject: [PATCH 2/4] =?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/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 | 115 - .../airflow/service/gapic_version.py | 16 - .../orchestration/airflow/service/py.typed | 2 - .../airflow/service_v1/__init__.py | 116 - .../airflow/service_v1/gapic_metadata.json | 242 - .../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 | 1739 ----- .../services/environments/client.py | 1951 ------ .../services/environments/pagers.py | 139 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 337 - .../services/environments/transports/grpc.py | 631 -- .../environments/transports/grpc_asyncio.py | 630 -- .../services/environments/transports/rest.py | 1803 ----- .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 464 -- .../services/image_versions/client.py | 660 -- .../services/image_versions/pagers.py | 139 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 176 - .../image_versions/transports/grpc.py | 319 - .../image_versions/transports/grpc_asyncio.py | 318 - .../image_versions/transports/rest.py | 534 -- .../airflow/service_v1/types/__init__.py | 108 - .../airflow/service_v1/types/environments.py | 2171 ------ .../service_v1/types/image_versions.py | 148 - .../airflow/service_v1/types/operations.py | 147 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 184 - .../v1/scripts/fixup_service_v1_keywords.py | 188 - .../v1/setup.py | 90 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.7.txt | 9 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../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 | 5935 ----------------- .../gapic/service_v1/test_image_versions.py | 2361 ------- .../v1beta1/.coveragerc | 13 - .../v1beta1/.flake8 | 33 - .../v1beta1/MANIFEST.in | 2 - .../v1beta1/README.rst | 49 - .../v1beta1/docs/conf.py | 376 -- .../v1beta1/docs/index.rst | 7 - .../docs/service_v1beta1/environments.rst | 10 - .../docs/service_v1beta1/image_versions.rst | 10 - .../v1beta1/docs/service_v1beta1/services.rst | 7 - .../v1beta1/docs/service_v1beta1/types.rst | 6 - .../orchestration/airflow/service/__init__.py | 105 - .../airflow/service/gapic_version.py | 16 - .../orchestration/airflow/service/py.typed | 2 - .../airflow/service_v1beta1/__init__.py | 106 - .../service_v1beta1/gapic_metadata.json | 197 - .../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 | 1552 ----- .../services/environments/client.py | 1761 ----- .../services/environments/pagers.py | 139 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 295 - .../services/environments/transports/grpc.py | 555 -- .../environments/transports/grpc_asyncio.py | 554 -- .../services/environments/transports/rest.py | 1470 ---- .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 464 -- .../services/image_versions/client.py | 660 -- .../services/image_versions/pagers.py | 139 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 176 - .../image_versions/transports/grpc.py | 319 - .../image_versions/transports/grpc_asyncio.py | 318 - .../image_versions/transports/rest.py | 534 -- .../airflow/service_v1beta1/types/__init__.py | 98 - .../service_v1beta1/types/environments.py | 2096 ------ .../service_v1beta1/types/image_versions.py | 148 - .../service_v1beta1/types/operations.py | 138 - .../v1beta1/mypy.ini | 3 - .../v1beta1/noxfile.py | 184 - .../scripts/fixup_service_v1beta1_keywords.py | 185 - .../v1beta1/setup.py | 90 - .../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 | 9 - .../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 | 5117 -------------- .../service_v1beta1/test_image_versions.py | 2361 ------- .../orchestration/airflow/service/__init__.py | 20 + .../airflow/service/gapic_version.py | 2 +- .../airflow/service_v1/__init__.py | 20 + .../airflow/service_v1/gapic_metadata.json | 75 + .../airflow/service_v1/gapic_version.py | 2 +- .../services/environments/async_client.py | 424 ++ .../services/environments/client.py | 431 ++ .../services/environments/transports/base.py | 82 + .../services/environments/transports/grpc.py | 143 + .../environments/transports/grpc_asyncio.py | 145 + .../services/environments/transports/rest.py | 651 ++ .../airflow/service_v1/types/__init__.py | 20 + .../airflow/service_v1/types/environments.py | 353 + .../airflow/service_v1/types/operations.py | 5 + .../airflow/service_v1beta1/gapic_version.py | 2 +- ...d_environments_create_environment_async.py | 0 ...ed_environments_create_environment_sync.py | 0 ...ed_environments_database_failover_async.py | 0 ...ted_environments_database_failover_sync.py | 0 ...d_environments_delete_environment_async.py | 0 ...ed_environments_delete_environment_sync.py | 0 ...ironments_execute_airflow_command_async.py | 0 ...vironments_execute_airflow_command_sync.py | 0 ...onments_fetch_database_properties_async.py | 0 ...ronments_fetch_database_properties_sync.py | 0 ...ated_environments_get_environment_async.py | 0 ...rated_environments_get_environment_sync.py | 0 ...ed_environments_list_environments_async.py | 0 ...ted_environments_list_environments_sync.py | 0 ...erated_environments_load_snapshot_async.py | 0 ...nerated_environments_load_snapshot_sync.py | 0 ...environments_poll_airflow_command_async.py | 0 ..._environments_poll_airflow_command_sync.py | 0 ...erated_environments_save_snapshot_async.py | 0 ...nerated_environments_save_snapshot_sync.py | 0 ...environments_stop_airflow_command_async.py | 0 ..._environments_stop_airflow_command_sync.py | 0 ...d_environments_update_environment_async.py | 0 ...ed_environments_update_environment_sync.py | 0 ...mage_versions_list_image_versions_async.py | 0 ...image_versions_list_image_versions_sync.py | 0 ...erated_environments_check_upgrade_async.py | 0 ...nerated_environments_check_upgrade_sync.py | 0 ...d_environments_create_environment_async.py | 0 ...ed_environments_create_environment_sync.py | 0 ...d_environments_delete_environment_async.py | 0 ...ed_environments_delete_environment_sync.py | 0 ...ated_environments_get_environment_async.py | 0 ...rated_environments_get_environment_sync.py | 0 ...ed_environments_list_environments_async.py | 0 ...ted_environments_list_environments_sync.py | 0 ...erated_environments_load_snapshot_async.py | 0 ...nerated_environments_load_snapshot_sync.py | 0 ...d_environments_restart_web_server_async.py | 0 ...ed_environments_restart_web_server_sync.py | 0 ...erated_environments_save_snapshot_async.py | 0 ...nerated_environments_save_snapshot_sync.py | 0 ...d_environments_update_environment_async.py | 0 ...ed_environments_update_environment_sync.py | 0 ...mage_versions_list_image_versions_async.py | 0 ...image_versions_list_image_versions_sync.py | 0 ...loud.orchestration.airflow.service.v1.json | 0 ...orchestration.airflow.service.v1beta1.json | 0 .../scripts/fixup_service_v1_keywords.py | 5 + .../gapic/service_v1/test_environments.py | 3132 ++++++--- 177 files changed, 4740 insertions(+), 43758 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/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/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/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/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 rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json (100%) 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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py deleted file mode 100644 index 55eb11f096a4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2022, 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 = None - -# 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 511c9ad31561..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CreateEnvironmentRequest -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 DeleteEnvironmentRequest -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 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 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 UpdateEnvironmentRequest -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', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'UpdateEnvironmentRequest', - '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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 366523066689..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CreateEnvironmentRequest -from .types.environments import DatabaseConfig -from .types.environments import DatabaseFailoverRequest -from .types.environments import DatabaseFailoverResponse -from .types.environments import DeleteEnvironmentRequest -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 IPAllocationPolicy -from .types.environments import ListEnvironmentsRequest -from .types.environments import ListEnvironmentsResponse -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 UpdateEnvironmentRequest -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', -'CreateEnvironmentRequest', -'DatabaseConfig', -'DatabaseFailoverRequest', -'DatabaseFailoverResponse', -'DeleteEnvironmentRequest', -'EncryptionConfig', -'Environment', -'EnvironmentConfig', -'EnvironmentsClient', -'ExecuteAirflowCommandRequest', -'ExecuteAirflowCommandResponse', -'FetchDatabasePropertiesRequest', -'FetchDatabasePropertiesResponse', -'GetEnvironmentRequest', -'IPAllocationPolicy', -'ImageVersion', -'ImageVersionsClient', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListImageVersionsRequest', -'ListImageVersionsResponse', -'LoadSnapshotRequest', -'LoadSnapshotResponse', -'MaintenanceWindow', -'MasterAuthorizedNetworksConfig', -'NetworkingConfig', -'NodeConfig', -'OperationMetadata', -'PollAirflowCommandRequest', -'PollAirflowCommandResponse', -'PrivateClusterConfig', -'PrivateEnvironmentConfig', -'RecoveryConfig', -'SaveSnapshotRequest', -'SaveSnapshotResponse', -'ScheduledSnapshotsConfig', -'SoftwareConfig', -'StopAirflowCommandRequest', -'StopAirflowCommandResponse', -'UpdateEnvironmentRequest', -'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 e35a8b09bf99..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json +++ /dev/null @@ -1,242 +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" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "rest": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - } - } - }, - "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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 e8e1c3845db5..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 63bae46eaf47..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 4b37a1ba9e0b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py +++ /dev/null @@ -1,1739 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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 - - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - - environment_path = staticmethod(EnvironmentsClient.environment_path) - parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 - - get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.create_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_environments, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.StopAirflowCommandRequest(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.stop_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.PollAirflowCommandRequest(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.poll_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.SaveSnapshotRequest(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.save_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.LoadSnapshotRequest(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.load_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.DatabaseFailoverRequest(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.database_failover, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, - 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(( - ("environment", request.environment), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 09cc5463bf16..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py +++ /dev/null @@ -1,1951 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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 common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.GetEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.ListEnvironmentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.DeleteEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.ExecuteAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.StopAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.PollAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.SaveSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.LoadSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.DatabaseFailoverRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.FetchDatabasePropertiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 61dda03258a4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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) 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 9384fe0b2c46..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 51d0225f04d6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py +++ /dev/null @@ -1,337 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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.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 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 48ad6fda5f55..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py +++ /dev/null @@ -1,631 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 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 14cc807c075d..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,630 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.orchestration.airflow.service_v1.types import environments -from google.longrunning import operations_pb2 -from google.longrunning import operations_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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def 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 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 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 76cdeabf2fbf..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py +++ /dev/null @@ -1,1803 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1.types import environments -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_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_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_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_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 - - 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_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_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_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_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_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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_environment(resp) - return resp - - 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(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 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 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 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 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 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 c8beb58456d9..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 331abbfbda40..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,464 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.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 -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 - - DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - - 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 - - get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_image_versions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 5883379867ba..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py +++ /dev/null @@ -1,660 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ImageVersionsTransport): - # transport is a ImageVersionsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_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.') - - # Minor optimization to avoid making a copy if the user passes - # in a image_versions.ListImageVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 328e922af2cb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 a11e27f277bb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 8511a3e8d148..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,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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 fafc0ffbf30f..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,319 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 52c70b26d13d..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,318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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 -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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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 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 06cb8c005fc8..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,534 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1.types import image_versions - -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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 2fdc02aaa78b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py +++ /dev/null @@ -1,108 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, - CreateEnvironmentRequest, - DatabaseConfig, - DatabaseFailoverRequest, - DatabaseFailoverResponse, - DeleteEnvironmentRequest, - EncryptionConfig, - Environment, - EnvironmentConfig, - ExecuteAirflowCommandRequest, - ExecuteAirflowCommandResponse, - FetchDatabasePropertiesRequest, - FetchDatabasePropertiesResponse, - GetEnvironmentRequest, - IPAllocationPolicy, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - LoadSnapshotRequest, - LoadSnapshotResponse, - MaintenanceWindow, - MasterAuthorizedNetworksConfig, - NetworkingConfig, - NodeConfig, - PollAirflowCommandRequest, - PollAirflowCommandResponse, - PrivateClusterConfig, - PrivateEnvironmentConfig, - RecoveryConfig, - SaveSnapshotRequest, - SaveSnapshotResponse, - ScheduledSnapshotsConfig, - SoftwareConfig, - StopAirflowCommandRequest, - StopAirflowCommandResponse, - UpdateEnvironmentRequest, - WebServerConfig, - WebServerNetworkAccessControl, - WorkloadsConfig, -) -from .image_versions import ( - ImageVersion, - ListImageVersionsRequest, - ListImageVersionsResponse, -) -from .operations import ( - OperationMetadata, -) - -__all__ = ( - 'CheckUpgradeResponse', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'UpdateEnvironmentRequest', - '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 30ee1fcd3a68..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py +++ /dev/null @@ -1,2171 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'EnvironmentConfig', - 'WebServerNetworkAccessControl', - 'DatabaseConfig', - 'WebServerConfig', - 'EncryptionConfig', - 'MaintenanceWindow', - 'SoftwareConfig', - 'IPAllocationPolicy', - 'NodeConfig', - 'PrivateClusterConfig', - 'NetworkingConfig', - 'PrivateEnvironmentConfig', - 'WorkloadsConfig', - 'RecoveryConfig', - 'ScheduledSnapshotsConfig', - 'MasterAuthorizedNetworksConfig', - 'Environment', - '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_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 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_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. - """ - 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, - ) - - -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-*.*.*. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - - -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.*.*. - """ - - 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, - ) - - -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 - """ - - 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, - ) - - -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-*.*.*. - 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, - ) - 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. - """ - - 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, - ) - - 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, - ) - - -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 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. - """ - 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, - ) - - -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, - ) - - -__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 2bb874963b6c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 eefba0b0dc1c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 48efa670881b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/orchestration/airflow/service_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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 a5e0a38cc890..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', ), - 'database_failover': ('environment', ), - 'delete_environment': ('name', ), - 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), - 'fetch_database_properties': ('environment', ), - 'get_environment': ('name', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), - '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', ), - } - - 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 23b72c183665..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-orchestration-airflow' - - -description = "Google Cloud Orchestration Airflow API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/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 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +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.0 -proto-plus==1.22.0 -protobuf==3.19.5 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 8741e5d4da57..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py +++ /dev/null @@ -1,5935 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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 -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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 - - -@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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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, - ) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -@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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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: - 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(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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch - 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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - # 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] - assert args[0] == environments.StopAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.StopAirflowCommandRequest() - - # 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] - assert args[0] == environments.PollAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.PollAirflowCommandRequest() - - # 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.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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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] - assert args[0] == environments.DatabaseFailoverRequest() - - # 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: - 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(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] - assert args[0] == environments.DatabaseFailoverRequest() - - # 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] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - # 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: - 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(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] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - # 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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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" - - -@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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" - - -@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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" - - -@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 - pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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'] - - -@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 - pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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.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" - - -@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" - - -@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" - - -@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 - pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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_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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).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 - - pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() - 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', - '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.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_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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"): - 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"): - 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"): - 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, - 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 b63c0fe80da3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py +++ /dev/null @@ -1,2361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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 -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 - - -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 - - -@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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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: - 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(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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch - 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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() - 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"): - 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"): - 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"): - 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, - 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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py deleted file mode 100644 index 0de401396097..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2022, 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 = None - -# 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 0dc5c64403b5..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py +++ /dev/null @@ -1,105 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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 DatabaseConfig -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import DeleteEnvironmentRequest -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 ExecuteAirflowCommandResponse -from google.cloud.orchestration.airflow.service_v1beta1.types.environments import GetEnvironmentRequest -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 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 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 UpdateEnvironmentRequest -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', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'RestartWebServerRequest', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'UpdateEnvironmentRequest', - '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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 287fce0f4d42..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py +++ /dev/null @@ -1,106 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CheckUpgradeRequest -from .types.environments import CheckUpgradeResponse -from .types.environments import CloudDataLineageIntegration -from .types.environments import CreateEnvironmentRequest -from .types.environments import DatabaseConfig -from .types.environments import DeleteEnvironmentRequest -from .types.environments import EncryptionConfig -from .types.environments import Environment -from .types.environments import EnvironmentConfig -from .types.environments import ExecuteAirflowCommandResponse -from .types.environments import GetEnvironmentRequest -from .types.environments import IPAllocationPolicy -from .types.environments import ListEnvironmentsRequest -from .types.environments import ListEnvironmentsResponse -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 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 UpdateEnvironmentRequest -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', -'CheckUpgradeRequest', -'CheckUpgradeResponse', -'CloudDataLineageIntegration', -'CreateEnvironmentRequest', -'DatabaseConfig', -'DeleteEnvironmentRequest', -'EncryptionConfig', -'Environment', -'EnvironmentConfig', -'EnvironmentsClient', -'ExecuteAirflowCommandResponse', -'GetEnvironmentRequest', -'IPAllocationPolicy', -'ImageVersion', -'ImageVersionsClient', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListImageVersionsRequest', -'ListImageVersionsResponse', -'LoadSnapshotRequest', -'LoadSnapshotResponse', -'MaintenanceWindow', -'MasterAuthorizedNetworksConfig', -'NetworkingConfig', -'NodeConfig', -'OperationMetadata', -'PollAirflowCommandResponse', -'PrivateClusterConfig', -'PrivateEnvironmentConfig', -'RecoveryConfig', -'RestartWebServerRequest', -'SaveSnapshotRequest', -'SaveSnapshotResponse', -'ScheduledSnapshotsConfig', -'SoftwareConfig', -'UpdateEnvironmentRequest', -'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 1f120bab3d17..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,197 +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" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "RestartWebServer": { - "methods": [ - "restart_web_server" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "RestartWebServer": { - "methods": [ - "restart_web_server" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "rest": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "RestartWebServer": { - "methods": [ - "restart_web_server" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - } - } - }, - "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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 e8e1c3845db5..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 63bae46eaf47..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 cc89042165e1..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py +++ /dev/null @@ -1,1552 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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 - - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - - environment_path = staticmethod(EnvironmentsClient.environment_path) - parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 - - get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.create_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_environments, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.RestartWebServerRequest(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.restart_web_server, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.CheckUpgradeRequest(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.check_upgrade, - 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(( - ("environment", request.environment), - )), - ) - - # 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 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.SaveSnapshotRequest(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.save_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.LoadSnapshotRequest(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.load_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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 list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 1d81c379c6b6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py +++ /dev/null @@ -1,1761 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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 common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.GetEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.ListEnvironmentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.DeleteEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.RestartWebServerRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.CheckUpgradeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.SaveSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.LoadSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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 __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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 1c973713f7ad..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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) 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 9384fe0b2c46..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 3b1d4682c315..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py +++ /dev/null @@ -1,295 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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.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, - ), - } - - 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 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 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 6ed6d4b6e463..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py +++ /dev/null @@ -1,555 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 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'] - - 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 a25c2c24a016..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,554 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -from google.longrunning import operations_pb2 -from google.longrunning import operations_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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def 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 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'] - - 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 0993f1d61b9b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py +++ /dev/null @@ -1,1470 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -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_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_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_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_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_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_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 - - 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_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_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_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_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_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_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_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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_environment(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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_load_snapshot(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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_save_snapshot(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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(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 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 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 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 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 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 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 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 c8beb58456d9..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 3374d08e134f..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,464 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.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 -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 - - DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - - 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 - - get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_image_versions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 2f3b5a6f46a3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py +++ /dev/null @@ -1,660 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ImageVersionsTransport): - # transport is a ImageVersionsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_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.') - - # Minor optimization to avoid making a copy if the user passes - # in a image_versions.ListImageVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 3ae9fe2c0711..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 a11e27f277bb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 736c36ad0f7b..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,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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 69f0488c287a..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,319 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 3028a9bc9c05..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,318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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 -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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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 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 57c90e2340b2..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,534 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions - -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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 129e57b84ac1..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ( - CheckUpgradeRequest, - CheckUpgradeResponse, - CloudDataLineageIntegration, - CreateEnvironmentRequest, - DatabaseConfig, - DeleteEnvironmentRequest, - EncryptionConfig, - Environment, - EnvironmentConfig, - ExecuteAirflowCommandResponse, - GetEnvironmentRequest, - IPAllocationPolicy, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - LoadSnapshotRequest, - LoadSnapshotResponse, - MaintenanceWindow, - MasterAuthorizedNetworksConfig, - NetworkingConfig, - NodeConfig, - PollAirflowCommandResponse, - PrivateClusterConfig, - PrivateEnvironmentConfig, - RecoveryConfig, - RestartWebServerRequest, - SaveSnapshotRequest, - SaveSnapshotResponse, - ScheduledSnapshotsConfig, - SoftwareConfig, - UpdateEnvironmentRequest, - WebServerConfig, - WebServerNetworkAccessControl, - WorkloadsConfig, -) -from .image_versions import ( - ImageVersion, - ListImageVersionsRequest, - ListImageVersionsResponse, -) -from .operations import ( - OperationMetadata, -) - -__all__ = ( - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'RestartWebServerRequest', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'UpdateEnvironmentRequest', - '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 173ba73c4088..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py +++ /dev/null @@ -1,2096 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', - 'ExecuteAirflowCommandResponse', - 'PollAirflowCommandResponse', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'EnvironmentConfig', - 'WebServerNetworkAccessControl', - 'SoftwareConfig', - 'IPAllocationPolicy', - 'NodeConfig', - 'PrivateClusterConfig', - 'NetworkingConfig', - 'PrivateEnvironmentConfig', - 'DatabaseConfig', - 'WebServerConfig', - 'EncryptionConfig', - 'MaintenanceWindow', - 'WorkloadsConfig', - '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 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 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 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 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, Cloud Composer - components may be subject to maintenance at any - time. - 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. - """ - 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 - - 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', - ) - - -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. - """ - - 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', - ) - - -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 - """ - - 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, - ) - - -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-*.*.*. - 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, - ) - 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-*.*.*. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - - -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. - """ - - 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, - ) - - 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, - ) - - -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. - """ - 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, - ) - - -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 df8c10475773..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 5acd9b0e66ef..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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. - """ - TYPE_UNSPECIFIED = 0 - CREATE = 1 - DELETE = 2 - UPDATE = 3 - CHECK = 4 - SAVE_SNAPSHOT = 5 - LOAD_SNAPSHOT = 6 - - 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 f2e63423782c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/orchestration/airflow/service_v1beta1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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 a4ae0cb0021e..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py +++ /dev/null @@ -1,185 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', ), - 'delete_environment': ('name', ), - 'get_environment': ('name', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), - 'load_snapshot': ('environment', 'snapshot_path', 'skip_pypi_packages_installation', 'skip_environment_variables_setting', 'skip_airflow_overrides_setting', 'skip_gcs_data_copying', ), - 'restart_web_server': ('name', ), - 'save_snapshot': ('environment', 'snapshot_location', ), - 'update_environment': ('update_mask', 'name', 'environment', ), - } - - 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 050167f108da..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-orchestration-airflow-service' - - -description = "Google Cloud Orchestration Airflow Service API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/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 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +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.0 -proto-plus==1.22.0 -protobuf==3.19.5 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ee0691456267..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py +++ /dev/null @@ -1,5117 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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 -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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 - - -@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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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, - ) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -@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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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: - 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(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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch - 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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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] - assert args[0] == environments.RestartWebServerRequest() - - # 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: - 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(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] - assert args[0] == environments.RestartWebServerRequest() - - # 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] - assert args[0] == environments.CheckUpgradeRequest() - - # 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: - 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(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] - assert args[0] == environments.CheckUpgradeRequest() - - # 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.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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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.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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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" - - -@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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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_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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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" - - -@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" - - -@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" - - -@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.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" - - -@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" - - -@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' - ) - - -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 = mock.Mock() - 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', - 'save_snapshot', - 'load_snapshot', - '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.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 -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_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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"): - 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"): - 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"): - 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, - 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 f6d496ae6a70..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py +++ /dev/null @@ -1,2361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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 -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 - - -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 - - -@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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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: - 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(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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch - 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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() - 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"): - 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"): - 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"): - 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, - 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/__init__.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/__init__.py index 660dedc6ed5b..e92bcf8fcc2f 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/__init__.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service/__init__.py @@ -34,10 +34,16 @@ CheckUpgradeResponse, CreateEnvironmentRequest, DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, DeleteEnvironmentRequest, EncryptionConfig, Environment, EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, GetEnvironmentRequest, IPAllocationPolicy, ListEnvironmentsRequest, @@ -48,6 +54,8 @@ MasterAuthorizedNetworksConfig, NetworkingConfig, NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, PrivateClusterConfig, PrivateEnvironmentConfig, RecoveryConfig, @@ -55,6 +63,8 @@ SaveSnapshotResponse, ScheduledSnapshotsConfig, SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, UpdateEnvironmentRequest, WebServerConfig, WebServerNetworkAccessControl, @@ -77,10 +87,16 @@ "CheckUpgradeResponse", "CreateEnvironmentRequest", "DatabaseConfig", + "DatabaseFailoverRequest", + "DatabaseFailoverResponse", "DeleteEnvironmentRequest", "EncryptionConfig", "Environment", "EnvironmentConfig", + "ExecuteAirflowCommandRequest", + "ExecuteAirflowCommandResponse", + "FetchDatabasePropertiesRequest", + "FetchDatabasePropertiesResponse", "GetEnvironmentRequest", "IPAllocationPolicy", "ListEnvironmentsRequest", @@ -91,6 +107,8 @@ "MasterAuthorizedNetworksConfig", "NetworkingConfig", "NodeConfig", + "PollAirflowCommandRequest", + "PollAirflowCommandResponse", "PrivateClusterConfig", "PrivateEnvironmentConfig", "RecoveryConfig", @@ -98,6 +116,8 @@ "SaveSnapshotResponse", "ScheduledSnapshotsConfig", "SoftwareConfig", + "StopAirflowCommandRequest", + "StopAirflowCommandResponse", "UpdateEnvironmentRequest", "WebServerConfig", "WebServerNetworkAccessControl", 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 b334dccf50ad..405b1cebcf15 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.8.0" # {x-release-please-version} +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/__init__.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/__init__.py index e6c2aa5151f5..e506321a612b 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/__init__.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/__init__.py @@ -26,10 +26,16 @@ CheckUpgradeResponse, CreateEnvironmentRequest, DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, DeleteEnvironmentRequest, EncryptionConfig, Environment, EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, GetEnvironmentRequest, IPAllocationPolicy, ListEnvironmentsRequest, @@ -40,6 +46,8 @@ MasterAuthorizedNetworksConfig, NetworkingConfig, NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, PrivateClusterConfig, PrivateEnvironmentConfig, RecoveryConfig, @@ -47,6 +55,8 @@ SaveSnapshotResponse, ScheduledSnapshotsConfig, SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, UpdateEnvironmentRequest, WebServerConfig, WebServerNetworkAccessControl, @@ -65,11 +75,17 @@ "CheckUpgradeResponse", "CreateEnvironmentRequest", "DatabaseConfig", + "DatabaseFailoverRequest", + "DatabaseFailoverResponse", "DeleteEnvironmentRequest", "EncryptionConfig", "Environment", "EnvironmentConfig", "EnvironmentsClient", + "ExecuteAirflowCommandRequest", + "ExecuteAirflowCommandResponse", + "FetchDatabasePropertiesRequest", + "FetchDatabasePropertiesResponse", "GetEnvironmentRequest", "IPAllocationPolicy", "ImageVersion", @@ -85,6 +101,8 @@ "NetworkingConfig", "NodeConfig", "OperationMetadata", + "PollAirflowCommandRequest", + "PollAirflowCommandResponse", "PrivateClusterConfig", "PrivateEnvironmentConfig", "RecoveryConfig", @@ -92,6 +110,8 @@ "SaveSnapshotResponse", "ScheduledSnapshotsConfig", "SoftwareConfig", + "StopAirflowCommandRequest", + "StopAirflowCommandResponse", "UpdateEnvironmentRequest", "WebServerConfig", "WebServerNetworkAccessControl", diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json index 45eed94effa3..e35a8b09bf99 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json @@ -15,11 +15,26 @@ "create_environment" ] }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, "DeleteEnvironment": { "methods": [ "delete_environment" ] }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, "GetEnvironment": { "methods": [ "get_environment" @@ -35,11 +50,21 @@ "load_snapshot" ] }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, "SaveSnapshot": { "methods": [ "save_snapshot" ] }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" @@ -55,11 +80,26 @@ "create_environment" ] }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, "DeleteEnvironment": { "methods": [ "delete_environment" ] }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, "GetEnvironment": { "methods": [ "get_environment" @@ -75,11 +115,21 @@ "load_snapshot" ] }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, "SaveSnapshot": { "methods": [ "save_snapshot" ] }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" @@ -95,11 +145,26 @@ "create_environment" ] }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, "DeleteEnvironment": { "methods": [ "delete_environment" ] }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, "GetEnvironment": { "methods": [ "get_environment" @@ -115,11 +180,21 @@ "load_snapshot" ] }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, "SaveSnapshot": { "methods": [ "save_snapshot" ] }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" 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 b334dccf50ad..405b1cebcf15 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.8.0" # {x-release-please-version} +__version__ = "0.1.0" # {x-release-please-version} diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py index 04ab575f0dde..411435e605ec 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py @@ -994,6 +994,248 @@ async def sample_delete_environment(): # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, + 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( + (("environment", request.environment),) + ), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.StopAirflowCommandRequest(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.stop_airflow_command, + 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( + (("environment", request.environment),) + ), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.PollAirflowCommandRequest(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.poll_airflow_command, + 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( + (("environment", request.environment),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def save_snapshot( self, request: Optional[Union[environments.SaveSnapshotRequest, dict]] = None, @@ -1192,6 +1434,188 @@ async def sample_load_snapshot(): # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.DatabaseFailoverRequest(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.database_failover, + 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( + (("environment", request.environment),) + ), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, + 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( + (("environment", request.environment),) + ), + ) + + # 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, diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/client.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/client.py index cd16517552b4..0d6abb4c3438 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/client.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/client.py @@ -1227,6 +1227,251 @@ def sample_delete_environment(): # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.ExecuteAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.StopAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.PollAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def save_snapshot( self, request: Optional[Union[environments.SaveSnapshotRequest, dict]] = None, @@ -1427,6 +1672,192 @@ def sample_load_snapshot(): # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.DatabaseFailoverRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.FetchDatabasePropertiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "EnvironmentsClient": return self diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py index 71a67880f9b4..d5bbbcf1de2f 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py @@ -150,6 +150,21 @@ def _prep_wrapped_messages(self, client_info): 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.save_snapshot: gapic_v1.method.wrap_method( self.save_snapshot, default_timeout=None, @@ -160,6 +175,16 @@ def _prep_wrapped_messages(self, client_info): 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): @@ -224,6 +249,42 @@ def delete_environment( ]: 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 save_snapshot( self, @@ -242,6 +303,27 @@ def load_snapshot( ]: 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, diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py index 7e2ad1eabe9e..da1231e09f64 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py @@ -376,6 +376,93 @@ def delete_environment( ) 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 save_snapshot( self, @@ -434,6 +521,62 @@ def load_snapshot( ) 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() diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py index 73305f8d1584..b2e2c0b5b659 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc_asyncio.py @@ -390,6 +390,93 @@ def delete_environment( ) 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 save_snapshot( self, @@ -452,6 +539,64 @@ def load_snapshot( ) 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 close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py index b356a9223f24..81a9ae84f88a 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py @@ -80,6 +80,14 @@ def post_create_environment(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 @@ -88,6 +96,22 @@ def post_delete_environment(self, response): logging.log(f"Received response: {response}") return response + 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 @@ -112,6 +136,14 @@ 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 @@ -120,6 +152,14 @@ 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 @@ -157,6 +197,29 @@ def post_create_environment( """ 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, @@ -180,6 +243,52 @@ def post_delete_environment( """ return response + 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, @@ -249,6 +358,29 @@ def post_load_snapshot( """ 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, @@ -272,6 +404,29 @@ def post_save_snapshot( """ 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, @@ -593,6 +748,95 @@ def __call__( resp = self._interceptor.post_create_environment(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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_database_failover(resp) + return resp + class _DeleteEnvironment(EnvironmentsRestStub): def __hash__(self): return hash("DeleteEnvironment") @@ -671,6 +915,185 @@ def __call__( resp = self._interceptor.post_delete_environment(resp) return resp + 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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") @@ -914,6 +1337,94 @@ def __call__( 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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") @@ -1000,6 +1511,94 @@ def __call__( 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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") @@ -1095,6 +1694,14 @@ def create_environment( # In C++ this would require a dynamic_cast return self._CreateEnvironment(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, @@ -1103,6 +1710,28 @@ def delete_environment( # In C++ this would require a dynamic_cast return self._DeleteEnvironment(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, @@ -1129,6 +1758,17 @@ def load_snapshot( # 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, @@ -1137,6 +1777,17 @@ def save_snapshot( # 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, diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/__init__.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/__init__.py index 7f77a37d0ac2..669c4396c805 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/__init__.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/__init__.py @@ -17,10 +17,16 @@ CheckUpgradeResponse, CreateEnvironmentRequest, DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, DeleteEnvironmentRequest, EncryptionConfig, Environment, EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, GetEnvironmentRequest, IPAllocationPolicy, ListEnvironmentsRequest, @@ -31,6 +37,8 @@ MasterAuthorizedNetworksConfig, NetworkingConfig, NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, PrivateClusterConfig, PrivateEnvironmentConfig, RecoveryConfig, @@ -38,6 +46,8 @@ SaveSnapshotResponse, ScheduledSnapshotsConfig, SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, UpdateEnvironmentRequest, WebServerConfig, WebServerNetworkAccessControl, @@ -54,10 +64,16 @@ "CheckUpgradeResponse", "CreateEnvironmentRequest", "DatabaseConfig", + "DatabaseFailoverRequest", + "DatabaseFailoverResponse", "DeleteEnvironmentRequest", "EncryptionConfig", "Environment", "EnvironmentConfig", + "ExecuteAirflowCommandRequest", + "ExecuteAirflowCommandResponse", + "FetchDatabasePropertiesRequest", + "FetchDatabasePropertiesResponse", "GetEnvironmentRequest", "IPAllocationPolicy", "ListEnvironmentsRequest", @@ -68,6 +84,8 @@ "MasterAuthorizedNetworksConfig", "NetworkingConfig", "NodeConfig", + "PollAirflowCommandRequest", + "PollAirflowCommandResponse", "PrivateClusterConfig", "PrivateEnvironmentConfig", "RecoveryConfig", @@ -75,6 +93,8 @@ "SaveSnapshotResponse", "ScheduledSnapshotsConfig", "SoftwareConfig", + "StopAirflowCommandRequest", + "StopAirflowCommandResponse", "UpdateEnvironmentRequest", "WebServerConfig", "WebServerNetworkAccessControl", diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/environments.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/environments.py index 8d2aab84a96e..f74a45942dbd 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/environments.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/environments.py @@ -30,10 +30,20 @@ "ListEnvironmentsResponse", "DeleteEnvironmentRequest", "UpdateEnvironmentRequest", + "ExecuteAirflowCommandRequest", + "ExecuteAirflowCommandResponse", + "StopAirflowCommandRequest", + "StopAirflowCommandResponse", + "PollAirflowCommandRequest", + "PollAirflowCommandResponse", "SaveSnapshotRequest", "SaveSnapshotResponse", "LoadSnapshotRequest", "LoadSnapshotResponse", + "DatabaseFailoverRequest", + "DatabaseFailoverResponse", + "FetchDatabasePropertiesRequest", + "FetchDatabasePropertiesResponse", "EnvironmentConfig", "WebServerNetworkAccessControl", "DatabaseConfig", @@ -364,6 +374,256 @@ class UpdateEnvironmentRequest(proto.Message): ) +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 SaveSnapshotRequest(proto.Message): r"""Request to create a snapshot of a Cloud Composer environment. @@ -461,6 +721,75 @@ 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. @@ -563,6 +892,11 @@ class EnvironmentConfig(proto.Message): 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. """ class EnvironmentSize(proto.Enum): @@ -583,6 +917,20 @@ class EnvironmentSize(proto.Enum): 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, @@ -663,6 +1011,11 @@ class EnvironmentSize(proto.Enum): number=18, message="RecoveryConfig", ) + resilience_mode: ResilienceMode = proto.Field( + proto.ENUM, + number=19, + enum=ResilienceMode, + ) class WebServerNetworkAccessControl(proto.Message): diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/operations.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/operations.py index 364157297248..2842211d59cc 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/operations.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1/types/operations.py @@ -99,6 +99,10 @@ class Type(proto.Enum): 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 @@ -107,6 +111,7 @@ class Type(proto.Enum): CHECK = 4 SAVE_SNAPSHOT = 5 LOAD_SNAPSHOT = 6 + DATABASE_FAILOVER = 7 state: State = proto.Field( proto.ENUM, 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 b334dccf50ad..405b1cebcf15 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.8.0" # {x-release-please-version} +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_create_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_create_environment_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_database_failover_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_database_failover_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_delete_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_delete_environment_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_execute_airflow_command_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_fetch_database_properties_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_get_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_get_environment_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_list_environments_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_list_environments_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_load_snapshot_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_load_snapshot_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_poll_airflow_command_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_save_snapshot_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_save_snapshot_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_stop_airflow_command_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_update_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_environments_update_environment_sync.py 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/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_async.py 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/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1_generated_image_versions_list_image_versions_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_check_upgrade_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_create_environment_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_delete_environment_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_get_environment_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_list_environments_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_load_snapshot_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_restart_web_server_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_save_snapshot_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_update_environment_sync.py 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/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_async.py 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/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_image_versions_list_image_versions_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1/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 similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1.json diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/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 similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/snippet_metadata_google.cloud.orchestration.airflow.service.v1beta1.json diff --git a/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1_keywords.py b/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1_keywords.py index 31a0db1fc126..a5e0a38cc890 100644 --- a/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1_keywords.py +++ b/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1_keywords.py @@ -40,12 +40,17 @@ class serviceCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'create_environment': ('parent', 'environment', ), + 'database_failover': ('environment', ), 'delete_environment': ('name', ), + 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), + 'fetch_database_properties': ('environment', ), 'get_environment': ('name', ), 'list_environments': ('parent', 'page_size', 'page_token', ), 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), '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', ), } diff --git a/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1/test_environments.py b/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1/test_environments.py index 589f5ab3d15f..afd2db8d888c 100644 --- a/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1/test_environments.py +++ b/packages/google-cloud-orchestration-airflow/tests/unit/gapic/service_v1/test_environments.py @@ -2137,11 +2137,11 @@ async def test_delete_environment_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - environments.SaveSnapshotRequest, + environments.ExecuteAirflowCommandRequest, dict, ], ) -def test_save_snapshot(request_type, transport: str = "grpc"): +def test_execute_airflow_command(request_type, transport: str = "grpc"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2152,21 +2152,32 @@ def test_save_snapshot(request_type, transport: str = "grpc"): 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: + with mock.patch.object( + type(client.transport.execute_airflow_command), "__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) + 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] - assert args[0] == environments.SaveSnapshotRequest() + assert args[0] == environments.ExecuteAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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_save_snapshot_empty_call(): +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( @@ -2175,16 +2186,19 @@ def test_save_snapshot_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.save_snapshot), "__call__") as call: - client.save_snapshot() + with mock.patch.object( + type(client.transport.execute_airflow_command), "__call__" + ) as call: + client.execute_airflow_command() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest() + assert args[0] == environments.ExecuteAirflowCommandRequest() @pytest.mark.asyncio -async def test_save_snapshot_async( - transport: str = "grpc_asyncio", request_type=environments.SaveSnapshotRequest +async def test_execute_airflow_command_async( + transport: str = "grpc_asyncio", + request_type=environments.ExecuteAirflowCommandRequest, ): client = EnvironmentsAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2196,42 +2210,55 @@ async def test_save_snapshot_async( 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: + 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( - operations_pb2.Operation(name="operations/spam") + environments.ExecuteAirflowCommandResponse( + execution_id="execution_id_value", + pod="pod_value", + pod_namespace="pod_namespace_value", + error="error_value", + ) ) - response = await client.save_snapshot(request) + 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] - assert args[0] == environments.SaveSnapshotRequest() + assert args[0] == environments.ExecuteAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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_save_snapshot_async_from_dict(): - await test_save_snapshot_async(request_type=dict) +async def test_execute_airflow_command_async_from_dict(): + await test_execute_airflow_command_async(request_type=dict) -def test_save_snapshot_field_headers(): +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.SaveSnapshotRequest() + 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.save_snapshot), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.save_snapshot(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 @@ -2247,23 +2274,25 @@ def test_save_snapshot_field_headers(): @pytest.mark.asyncio -async def test_save_snapshot_field_headers_async(): +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.SaveSnapshotRequest() + 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.save_snapshot), "__call__") as call: + with mock.patch.object( + type(client.transport.execute_airflow_command), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + environments.ExecuteAirflowCommandResponse() ) - await client.save_snapshot(request) + await client.execute_airflow_command(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2281,11 +2310,11 @@ async def test_save_snapshot_field_headers_async(): @pytest.mark.parametrize( "request_type", [ - environments.LoadSnapshotRequest, + environments.StopAirflowCommandRequest, dict, ], ) -def test_load_snapshot(request_type, transport: str = "grpc"): +def test_stop_airflow_command(request_type, transport: str = "grpc"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2296,21 +2325,28 @@ def test_load_snapshot(request_type, transport: str = "grpc"): 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: + with mock.patch.object( + type(client.transport.stop_airflow_command), "__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) + 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] - assert args[0] == environments.LoadSnapshotRequest() + assert args[0] == environments.StopAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ["output_value"] -def test_load_snapshot_empty_call(): +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( @@ -2319,16 +2355,18 @@ def test_load_snapshot_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.load_snapshot), "__call__") as call: - client.load_snapshot() + with mock.patch.object( + type(client.transport.stop_airflow_command), "__call__" + ) as call: + client.stop_airflow_command() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest() + assert args[0] == environments.StopAirflowCommandRequest() @pytest.mark.asyncio -async def test_load_snapshot_async( - transport: str = "grpc_asyncio", request_type=environments.LoadSnapshotRequest +async def test_stop_airflow_command_async( + transport: str = "grpc_asyncio", request_type=environments.StopAirflowCommandRequest ): client = EnvironmentsAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2340,42 +2378,51 @@ async def test_load_snapshot_async( 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: + 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( - operations_pb2.Operation(name="operations/spam") + environments.StopAirflowCommandResponse( + is_done=True, + output=["output_value"], + ) ) - response = await client.load_snapshot(request) + 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] - assert args[0] == environments.LoadSnapshotRequest() + assert args[0] == environments.StopAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ["output_value"] @pytest.mark.asyncio -async def test_load_snapshot_async_from_dict(): - await test_load_snapshot_async(request_type=dict) +async def test_stop_airflow_command_async_from_dict(): + await test_stop_airflow_command_async(request_type=dict) -def test_load_snapshot_field_headers(): +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.LoadSnapshotRequest() + 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.load_snapshot), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.load_snapshot(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 @@ -2391,23 +2438,25 @@ def test_load_snapshot_field_headers(): @pytest.mark.asyncio -async def test_load_snapshot_field_headers_async(): +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.LoadSnapshotRequest() + 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.load_snapshot), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_airflow_command), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + environments.StopAirflowCommandResponse() ) - await client.load_snapshot(request) + await client.stop_airflow_command(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2425,173 +2474,1763 @@ async def test_load_snapshot_field_headers_async(): @pytest.mark.parametrize( "request_type", [ - environments.CreateEnvironmentRequest, + environments.PollAirflowCommandRequest, dict, ], ) -def test_create_environment_rest(request_type): +def test_poll_airflow_command(request_type, transport: str = "grpc"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # 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, - }, - "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, - }, - "private_environment_config": { - "enable_private_environment": 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"}, - "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, - }, - }, - "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", - } - }, - }, - "uuid": "uuid_value", - "state": 1, - "create_time": {}, - "update_time": {}, - "labels": {}, - } - request = request_type(**request_init) - - # Mock the http request call within the method and 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") + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_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: + # Designate an appropriate return value for the call. + call.return_value = environments.PollAirflowCommandResponse( + output_end=True, + ) + response = client.poll_airflow_command(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - 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] + assert args[0] == environments.PollAirflowCommandRequest() # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( +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(), - interceptor=None - if null_interceptor - else transports.EnvironmentsRestInterceptor(), + transport="grpc", ) - client = EnvironmentsClient(transport=transport) + + # Mock the actual call within the gRPC stub, and fake the request. 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, - } + type(client.transport.poll_airflow_command), "__call__" + ) as call: + 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( + 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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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.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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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: + 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( + 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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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: + 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( + 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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: + 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( + 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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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: + 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( + 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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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, + }, + "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, + }, + "private_environment_config": { + "enable_private_environment": 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"}, + "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, + }, + }, + "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, + }, + "uuid": "uuid_value", + "state": 1, + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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, + }, + "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, + }, + "private_environment_config": { + "enable_private_environment": 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"}, + "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, + }, + }, + "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, + }, + "uuid": "uuid_value", + "state": 1, + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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" + + +@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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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, + }, + "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, + }, + "private_environment_config": { + "enable_private_environment": 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"}, + "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, + }, + }, + "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, + }, + "uuid": "uuid_value", + "state": 1, + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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 @@ -2600,7 +4239,7 @@ def test_create_environment_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = environments.CreateEnvironmentRequest() + request = environments.UpdateEnvironmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -2608,7 +4247,7 @@ def test_create_environment_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_environment( + client.update_environment( request, metadata=[ ("key", "val"), @@ -2620,8 +4259,8 @@ def test_create_environment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_environment_rest_bad_request( - transport: str = "rest", request_type=environments.CreateEnvironmentRequest +def test_update_environment_rest_bad_request( + transport: str = "rest", request_type=environments.UpdateEnvironmentRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2629,7 +4268,7 @@ def test_create_environment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/environments/sample3"} request_init["environment"] = { "name": "name_value", "config": { @@ -2727,6 +4366,7 @@ def test_create_environment_rest_bad_request( "time_zone": "time_zone_value", } }, + "resilience_mode": 1, }, "uuid": "uuid_value", "state": 1, @@ -2745,10 +4385,10 @@ def test_create_environment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_environment(request) + client.update_environment(request) -def test_create_environment_rest_flattened(): +def test_update_environment_rest_flattened(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2760,12 +4400,15 @@ def test_create_environment_rest_flattened(): 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"} + sample_request = { + "name": "projects/sample1/locations/sample2/environments/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", environment=environments.Environment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -2776,20 +4419,20 @@ def test_create_environment_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_environment(**mock_args) + 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/{parent=projects/*/locations/*}/environments" + "%s/v1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1], ) -def test_create_environment_rest_flattened_error(transport: str = "rest"): +def test_update_environment_rest_flattened_error(transport: str = "rest"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2798,14 +4441,15 @@ def test_create_environment_rest_flattened_error(transport: str = "rest"): # 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", + 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_create_environment_rest_error(): +def test_update_environment_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2814,11 +4458,11 @@ def test_create_environment_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.GetEnvironmentRequest, + environments.DeleteEnvironmentRequest, dict, ], ) -def test_get_environment_rest(request_type): +def test_delete_environment_rest(request_type): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2831,31 +4475,23 @@ def test_get_environment_rest(request_type): # Mock the http request call within the method and 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, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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) + response = client.delete_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.operation.name == "operations/spam" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_environment_rest_interceptors(null_interceptor): +def test_delete_environment_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -2868,14 +4504,16 @@ def test_get_environment_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_get_environment" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EnvironmentsRestInterceptor, "post_delete_environment" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_get_environment" + transports.EnvironmentsRestInterceptor, "pre_delete_environment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.GetEnvironmentRequest.pb( - environments.GetEnvironmentRequest() + pb_message = environments.DeleteEnvironmentRequest.pb( + environments.DeleteEnvironmentRequest() ) transcode.return_value = { "method": "post", @@ -2887,19 +4525,19 @@ def test_get_environment_rest_interceptors(null_interceptor): 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() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = environments.GetEnvironmentRequest() + request = environments.DeleteEnvironmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = environments.Environment() + post.return_value = operations_pb2.Operation() - client.get_environment( + client.delete_environment( request, metadata=[ ("key", "val"), @@ -2911,8 +4549,8 @@ def test_get_environment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_environment_rest_bad_request( - transport: str = "rest", request_type=environments.GetEnvironmentRequest +def test_delete_environment_rest_bad_request( + transport: str = "rest", request_type=environments.DeleteEnvironmentRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2932,10 +4570,10 @@ def test_get_environment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_environment(request) + client.delete_environment(request) -def test_get_environment_rest_flattened(): +def test_delete_environment_rest_flattened(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2944,7 +4582,7 @@ def test_get_environment_rest_flattened(): # Mock the http request call within the method and 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() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -2960,12 +4598,11 @@ def test_get_environment_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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) + client.delete_environment(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -2978,7 +4615,7 @@ def test_get_environment_rest_flattened(): ) -def test_get_environment_rest_flattened_error(transport: str = "rest"): +def test_delete_environment_rest_flattened_error(transport: str = "rest"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2987,13 +4624,13 @@ def test_get_environment_rest_flattened_error(transport: str = "rest"): # 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(), + client.delete_environment( + environments.DeleteEnvironmentRequest(), name="name_value", ) -def test_get_environment_rest_error(): +def test_delete_environment_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3002,44 +4639,52 @@ def test_get_environment_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.ListEnvironmentsRequest, + environments.ExecuteAirflowCommandRequest, dict, ], ) -def test_list_environments_rest(request_type): +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 = {"parent": "projects/sample1/locations/sample2"} + 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.ListEnvironmentsResponse( - next_page_token="next_page_token_value", + 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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_environments(request) + response = client.execute_airflow_command(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" + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == "execution_id_value" + assert response.pod == "pod_value" + assert response.pod_namespace == "pod_namespace_value" + assert response.error == "error_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_environments_rest_interceptors(null_interceptor): +def test_execute_airflow_command_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3052,14 +4697,14 @@ def test_list_environments_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_list_environments" + transports.EnvironmentsRestInterceptor, "post_execute_airflow_command" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_list_environments" + transports.EnvironmentsRestInterceptor, "pre_execute_airflow_command" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.ListEnvironmentsRequest.pb( - environments.ListEnvironmentsRequest() + pb_message = environments.ExecuteAirflowCommandRequest.pb( + environments.ExecuteAirflowCommandRequest() ) transcode.return_value = { "method": "post", @@ -3071,19 +4716,19 @@ def test_list_environments_rest_interceptors(null_interceptor): 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() + req.return_value._content = environments.ExecuteAirflowCommandResponse.to_json( + environments.ExecuteAirflowCommandResponse() ) - request = environments.ListEnvironmentsRequest() + request = environments.ExecuteAirflowCommandRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = environments.ListEnvironmentsResponse() + post.return_value = environments.ExecuteAirflowCommandResponse() - client.list_environments( + client.execute_airflow_command( request, metadata=[ ("key", "val"), @@ -3095,8 +4740,8 @@ def test_list_environments_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_environments_rest_bad_request( - transport: str = "rest", request_type=environments.ListEnvironmentsRequest +def test_execute_airflow_command_rest_bad_request( + transport: str = "rest", request_type=environments.ExecuteAirflowCommandRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3104,281 +4749,74 @@ def test_list_environments_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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.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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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, - }, - "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, - }, - "private_environment_config": { - "enable_private_environment": 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"}, - "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, - }, - }, - "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", - } - }, - }, - "uuid": "uuid_value", - "state": 1, - "create_time": {}, - "update_time": {}, - "labels": {}, + # 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 = operations_pb2.Operation(name="operations/spam") + 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 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_environment(request) + response = client.stop_airflow_command(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ["output_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_environment_rest_interceptors(null_interceptor): +def test_stop_airflow_command_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3391,16 +4829,14 @@ def test_update_environment_rest_interceptors(null_interceptor): ) 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" + transports.EnvironmentsRestInterceptor, "post_stop_airflow_command" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_update_environment" + transports.EnvironmentsRestInterceptor, "pre_stop_airflow_command" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.UpdateEnvironmentRequest.pb( - environments.UpdateEnvironmentRequest() + pb_message = environments.StopAirflowCommandRequest.pb( + environments.StopAirflowCommandRequest() ) transcode.return_value = { "method": "post", @@ -3412,19 +4848,19 @@ def test_update_environment_rest_interceptors(null_interceptor): 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() + req.return_value._content = environments.StopAirflowCommandResponse.to_json( + environments.StopAirflowCommandResponse() ) - request = environments.UpdateEnvironmentRequest() + request = environments.StopAirflowCommandRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = environments.StopAirflowCommandResponse() - client.update_environment( + client.stop_airflow_command( request, metadata=[ ("key", "val"), @@ -3436,8 +4872,8 @@ def test_update_environment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_environment_rest_bad_request( - transport: str = "rest", request_type=environments.UpdateEnvironmentRequest +def test_stop_airflow_command_rest_bad_request( + transport: str = "rest", request_type=environments.StopAirflowCommandRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3445,110 +4881,8 @@ def test_update_environment_rest_bad_request( ) # 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, - }, - "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, - }, - "private_environment_config": { - "enable_private_environment": 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"}, - "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, - }, - }, - "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", - } - }, - }, - "uuid": "uuid_value", - "state": 1, - "create_time": {}, - "update_time": {}, - "labels": {}, + request_init = { + "environment": "projects/sample1/locations/sample2/environments/sample3" } request = request_type(**request_init) @@ -3561,71 +4895,140 @@ def test_update_environment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_environment(request) + client.stop_airflow_command(request) -def test_update_environment_rest_flattened(): +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 = 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"]), + return_value = environments.PollAirflowCommandResponse( + output_end=True, ) - 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) + pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.poll_airflow_command(request) - client.update_environment(**mock_args) + # Establish that the response is the type that we expect. + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True - # 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], + +@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() -def test_update_environment_rest_flattened_error(transport: str = "rest"): + 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, ) - # 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"]), - ) + # 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_update_environment_rest_error(): +def test_poll_airflow_command_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3634,18 +5037,20 @@ def test_update_environment_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.DeleteEnvironmentRequest, + environments.SaveSnapshotRequest, dict, ], ) -def test_delete_environment_rest(request_type): +def test_save_snapshot_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": "projects/sample1/locations/sample2/environments/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -3660,14 +5065,14 @@ def test_delete_environment_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_environment(request) + response = client.save_snapshot(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_environment_rest_interceptors(null_interceptor): +def test_save_snapshot_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3682,14 +5087,14 @@ def test_delete_environment_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_delete_environment" + transports.EnvironmentsRestInterceptor, "post_save_snapshot" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_delete_environment" + transports.EnvironmentsRestInterceptor, "pre_save_snapshot" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.DeleteEnvironmentRequest.pb( - environments.DeleteEnvironmentRequest() + pb_message = environments.SaveSnapshotRequest.pb( + environments.SaveSnapshotRequest() ) transcode.return_value = { "method": "post", @@ -3705,7 +5110,7 @@ def test_delete_environment_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = environments.DeleteEnvironmentRequest() + request = environments.SaveSnapshotRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -3713,7 +5118,7 @@ def test_delete_environment_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_environment( + client.save_snapshot( request, metadata=[ ("key", "val"), @@ -3725,8 +5130,8 @@ def test_delete_environment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_environment_rest_bad_request( - transport: str = "rest", request_type=environments.DeleteEnvironmentRequest +def test_save_snapshot_rest_bad_request( + transport: str = "rest", request_type=environments.SaveSnapshotRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3734,7 +5139,9 @@ def test_delete_environment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/environments/sample3"} + 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. @@ -3746,67 +5153,138 @@ def test_delete_environment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_environment(request) + client.save_snapshot(request) -def test_delete_environment_rest_flattened(): +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") - # 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 + response = client.load_snapshot(request) - client.delete_environment(**mock_args) + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" - # 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], + +@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() -def test_delete_environment_rest_flattened_error(transport: str = "rest"): + 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, ) - # 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", - ) + # 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_delete_environment_rest_error(): + +def test_load_snapshot_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3815,11 +5293,11 @@ def test_delete_environment_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.SaveSnapshotRequest, + environments.DatabaseFailoverRequest, dict, ], ) -def test_save_snapshot_rest(request_type): +def test_database_failover_rest(request_type): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3843,14 +5321,14 @@ def test_save_snapshot_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.save_snapshot(request) + response = client.database_failover(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_save_snapshot_rest_interceptors(null_interceptor): +def test_database_failover_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3865,14 +5343,14 @@ def test_save_snapshot_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_save_snapshot" + transports.EnvironmentsRestInterceptor, "post_database_failover" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_save_snapshot" + transports.EnvironmentsRestInterceptor, "pre_database_failover" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.SaveSnapshotRequest.pb( - environments.SaveSnapshotRequest() + pb_message = environments.DatabaseFailoverRequest.pb( + environments.DatabaseFailoverRequest() ) transcode.return_value = { "method": "post", @@ -3888,7 +5366,7 @@ def test_save_snapshot_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = environments.SaveSnapshotRequest() + request = environments.DatabaseFailoverRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -3896,7 +5374,7 @@ def test_save_snapshot_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.save_snapshot( + client.database_failover( request, metadata=[ ("key", "val"), @@ -3908,8 +5386,8 @@ def test_save_snapshot_rest_interceptors(null_interceptor): post.assert_called_once() -def test_save_snapshot_rest_bad_request( - transport: str = "rest", request_type=environments.SaveSnapshotRequest +def test_database_failover_rest_bad_request( + transport: str = "rest", request_type=environments.DatabaseFailoverRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3931,10 +5409,10 @@ def test_save_snapshot_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.save_snapshot(request) + client.database_failover(request) -def test_save_snapshot_rest_error(): +def test_database_failover_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3943,11 +5421,11 @@ def test_save_snapshot_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.LoadSnapshotRequest, + environments.FetchDatabasePropertiesRequest, dict, ], ) -def test_load_snapshot_rest(request_type): +def test_fetch_database_properties_rest(request_type): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3962,23 +5440,119 @@ def test_load_snapshot_rest(request_type): # Mock the http request call within the method and 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") + 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 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.load_snapshot(request) + response = client.fetch_database_properties(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + 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_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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).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 + + pb_return_value = environments.FetchDatabasePropertiesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_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_load_snapshot_rest_interceptors(null_interceptor): +def test_fetch_database_properties_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3991,16 +5565,14 @@ def test_load_snapshot_rest_interceptors(null_interceptor): ) 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" + transports.EnvironmentsRestInterceptor, "post_fetch_database_properties" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_load_snapshot" + transports.EnvironmentsRestInterceptor, "pre_fetch_database_properties" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.LoadSnapshotRequest.pb( - environments.LoadSnapshotRequest() + pb_message = environments.FetchDatabasePropertiesRequest.pb( + environments.FetchDatabasePropertiesRequest() ) transcode.return_value = { "method": "post", @@ -4012,19 +5584,21 @@ def test_load_snapshot_rest_interceptors(null_interceptor): 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() + req.return_value._content = ( + environments.FetchDatabasePropertiesResponse.to_json( + environments.FetchDatabasePropertiesResponse() + ) ) - request = environments.LoadSnapshotRequest() + request = environments.FetchDatabasePropertiesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = environments.FetchDatabasePropertiesResponse() - client.load_snapshot( + client.fetch_database_properties( request, metadata=[ ("key", "val"), @@ -4036,8 +5610,8 @@ def test_load_snapshot_rest_interceptors(null_interceptor): post.assert_called_once() -def test_load_snapshot_rest_bad_request( - transport: str = "rest", request_type=environments.LoadSnapshotRequest +def test_fetch_database_properties_rest_bad_request( + transport: str = "rest", request_type=environments.FetchDatabasePropertiesRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4059,10 +5633,10 @@ def test_load_snapshot_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.load_snapshot(request) + client.fetch_database_properties(request) -def test_load_snapshot_rest_error(): +def test_fetch_database_properties_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4212,8 +5786,13 @@ def test_environments_base_transport(): "list_environments", "update_environment", "delete_environment", + "execute_airflow_command", + "stop_airflow_command", + "poll_airflow_command", "save_snapshot", "load_snapshot", + "database_failover", + "fetch_database_properties", "get_operation", "delete_operation", "list_operations", @@ -4509,12 +6088,27 @@ def test_environments_client_transport_session_collision(transport_name): 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.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(): From e52cdc75c0ab6d99d6bba16d14523cb289711555 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 13 Jun 2023 22:51:01 +0000 Subject: [PATCH 3/4] feat: added RPCs StopAirflowCommand, ExecuteAirflowCommand, PollAirflowCommand, DatabaseFailover, FetchDatabaseProperties PiperOrigin-RevId: 540052133 Source-Link: https://github.com/googleapis/googleapis/commit/386f722b6251585d42b1698ce433b1b55010eb11 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b8b5220bb0ca29e108194248def0dbb38b068769 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW9yY2hlc3RyYXRpb24tYWlyZmxvdy8uT3dsQm90LnlhbWwiLCJoIjoiYjhiNTIyMGJiMGNhMjllMTA4MTk0MjQ4ZGVmMGRiYjM4YjA2ODc2OSJ9 --- .../v1/.coveragerc | 13 + .../v1/.flake8 | 33 + .../v1/MANIFEST.in | 2 + .../v1/README.rst | 49 + .../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 | 115 + .../airflow/service/gapic_version.py | 16 + .../orchestration/airflow/service/py.typed | 2 + .../airflow/service_v1/__init__.py | 116 + .../airflow/service_v1/gapic_metadata.json | 242 + .../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 | 1739 +++++ .../services/environments/client.py | 1951 +++++ .../services/environments/pagers.py | 139 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 337 + .../services/environments/transports/grpc.py | 631 ++ .../environments/transports/grpc_asyncio.py | 630 ++ .../services/environments/transports/rest.py | 1803 +++++ .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 464 ++ .../services/image_versions/client.py | 660 ++ .../services/image_versions/pagers.py | 139 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 176 + .../image_versions/transports/grpc.py | 319 + .../image_versions/transports/grpc_asyncio.py | 318 + .../image_versions/transports/rest.py | 534 ++ .../airflow/service_v1/types/__init__.py | 108 + .../airflow/service_v1/types/environments.py | 2171 ++++++ .../service_v1/types/image_versions.py | 148 + .../airflow/service_v1/types/operations.py | 147 + .../v1/mypy.ini | 3 + .../v1/noxfile.py | 184 + ...d_environments_create_environment_async.py | 55 + ...ed_environments_create_environment_sync.py | 55 + ...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 + ...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 + ...ed_environments_list_environments_async.py | 52 + ...ted_environments_list_environments_sync.py | 52 + ...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 + ...mage_versions_list_image_versions_async.py | 52 + ...image_versions_list_image_versions_sync.py | 52 + ...loud.orchestration.airflow.service.v1.json | 2076 ++++++ .../v1/scripts/fixup_service_v1_keywords.py | 188 + .../v1/setup.py | 90 + .../v1/testing/constraints-3.10.txt | 6 + .../v1/testing/constraints-3.11.txt | 6 + .../v1/testing/constraints-3.12.txt | 6 + .../v1/testing/constraints-3.7.txt | 9 + .../v1/testing/constraints-3.8.txt | 6 + .../v1/testing/constraints-3.9.txt | 6 + .../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 | 5935 +++++++++++++++ .../gapic/service_v1/test_image_versions.py | 2361 ++++++ .../v1beta1/.coveragerc | 13 + .../v1beta1/.flake8 | 33 + .../v1beta1/MANIFEST.in | 2 + .../v1beta1/README.rst | 49 + .../v1beta1/docs/conf.py | 376 + .../v1beta1/docs/index.rst | 7 + .../docs/service_v1beta1/environments.rst | 10 + .../docs/service_v1beta1/image_versions.rst | 10 + .../v1beta1/docs/service_v1beta1/services.rst | 7 + .../v1beta1/docs/service_v1beta1/types.rst | 6 + .../orchestration/airflow/service/__init__.py | 121 + .../airflow/service/gapic_version.py | 16 + .../orchestration/airflow/service/py.typed | 2 + .../airflow/service_v1beta1/__init__.py | 122 + .../service_v1beta1/gapic_metadata.json | 272 + .../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 | 1967 +++++ .../services/environments/client.py | 2181 ++++++ .../services/environments/pagers.py | 139 + .../environments/transports/__init__.py | 38 + .../services/environments/transports/base.py | 365 + .../services/environments/transports/grpc.py | 686 ++ .../environments/transports/grpc_asyncio.py | 685 ++ .../services/environments/transports/rest.py | 2036 ++++++ .../services/image_versions/__init__.py | 22 + .../services/image_versions/async_client.py | 464 ++ .../services/image_versions/client.py | 660 ++ .../services/image_versions/pagers.py | 139 + .../image_versions/transports/__init__.py | 38 + .../image_versions/transports/base.py | 176 + .../image_versions/transports/grpc.py | 319 + .../image_versions/transports/grpc_asyncio.py | 318 + .../image_versions/transports/rest.py | 534 ++ .../airflow/service_v1beta1/types/__init__.py | 114 + .../service_v1beta1/types/environments.py | 2344 ++++++ .../service_v1beta1/types/image_versions.py | 148 + .../service_v1beta1/types/operations.py | 143 + .../v1beta1/mypy.ini | 3 + .../v1beta1/noxfile.py | 184 + ...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 + ...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 + ...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 + ...ed_environments_list_environments_async.py | 52 + ...ted_environments_list_environments_sync.py | 52 + ...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 + ...mage_versions_list_image_versions_async.py | 52 + ...image_versions_list_image_versions_sync.py | 52 + ...orchestration.airflow.service.v1beta1.json | 2382 ++++++ .../scripts/fixup_service_v1beta1_keywords.py | 190 + .../v1beta1/setup.py | 90 + .../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 | 9 + .../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 | 6509 +++++++++++++++++ .../service_v1beta1/test_image_versions.py | 2361 ++++++ 170 files changed, 53930 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/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_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_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_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_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_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/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_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_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_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_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_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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py new file mode 100644 index 000000000000..55eb11f096a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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"2022, 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 = None + +# 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..511c9ad31561 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CreateEnvironmentRequest +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 DeleteEnvironmentRequest +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 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 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 UpdateEnvironmentRequest +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', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'UpdateEnvironmentRequest', + '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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..366523066689 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py @@ -0,0 +1,116 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CreateEnvironmentRequest +from .types.environments import DatabaseConfig +from .types.environments import DatabaseFailoverRequest +from .types.environments import DatabaseFailoverResponse +from .types.environments import DeleteEnvironmentRequest +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 IPAllocationPolicy +from .types.environments import ListEnvironmentsRequest +from .types.environments import ListEnvironmentsResponse +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 UpdateEnvironmentRequest +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', +'CreateEnvironmentRequest', +'DatabaseConfig', +'DatabaseFailoverRequest', +'DatabaseFailoverResponse', +'DeleteEnvironmentRequest', +'EncryptionConfig', +'Environment', +'EnvironmentConfig', +'EnvironmentsClient', +'ExecuteAirflowCommandRequest', +'ExecuteAirflowCommandResponse', +'FetchDatabasePropertiesRequest', +'FetchDatabasePropertiesResponse', +'GetEnvironmentRequest', +'IPAllocationPolicy', +'ImageVersion', +'ImageVersionsClient', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListImageVersionsRequest', +'ListImageVersionsResponse', +'LoadSnapshotRequest', +'LoadSnapshotResponse', +'MaintenanceWindow', +'MasterAuthorizedNetworksConfig', +'NetworkingConfig', +'NodeConfig', +'OperationMetadata', +'PollAirflowCommandRequest', +'PollAirflowCommandResponse', +'PrivateClusterConfig', +'PrivateEnvironmentConfig', +'RecoveryConfig', +'SaveSnapshotRequest', +'SaveSnapshotResponse', +'ScheduledSnapshotsConfig', +'SoftwareConfig', +'StopAirflowCommandRequest', +'StopAirflowCommandResponse', +'UpdateEnvironmentRequest', +'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..e35a8b09bf99 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json @@ -0,0 +1,242 @@ + { + "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" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "LoadSnapshot": { + "methods": [ + "load_snapshot" + ] + }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, + "SaveSnapshot": { + "methods": [ + "save_snapshot" + ] + }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, + "UpdateEnvironment": { + "methods": [ + "update_environment" + ] + } + } + } + } + }, + "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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..e8e1c3845db5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..63bae46eaf47 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..4b37a1ba9e0b --- /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,1739 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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 + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 + + get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_environments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.StopAirflowCommandRequest(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.stop_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.PollAirflowCommandRequest(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.poll_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.SaveSnapshotRequest(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.save_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.LoadSnapshotRequest(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.load_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.DatabaseFailoverRequest(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.database_failover, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, + 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(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..09cc5463bf16 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py @@ -0,0 +1,1951 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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 common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.ListEnvironmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.ExecuteAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.StopAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.PollAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.SaveSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.LoadSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.DatabaseFailoverRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.FetchDatabasePropertiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..61dda03258a4 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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) 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..9384fe0b2c46 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..51d0225f04d6 --- /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,337 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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.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 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..48ad6fda5f55 --- /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,631 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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 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..14cc807c075d --- /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,630 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.orchestration.airflow.service_v1.types import environments +from google.longrunning import operations_pb2 +from google.longrunning import operations_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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def 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 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 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..76cdeabf2fbf --- /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,1803 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1.types import environments +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_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_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_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_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 + + 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_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_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_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_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_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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_environment(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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_environment(resp) + return resp + + 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_environment(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 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 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 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 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 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..c8beb58456d9 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..331abbfbda40 --- /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,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.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 +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 + + DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + + 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 + + get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_image_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..5883379867ba --- /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,660 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # 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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageVersionsTransport): + # transport is a ImageVersionsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_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.') + + # Minor optimization to avoid making a copy if the user passes + # in a image_versions.ListImageVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..328e922af2cb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..a11e27f277bb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..8511a3e8d148 --- /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,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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..fafc0ffbf30f --- /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,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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..52c70b26d13d --- /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,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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 +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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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 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..06cb8c005fc8 --- /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,534 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1.types import image_versions + +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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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..2fdc02aaa78b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, + CreateEnvironmentRequest, + DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, + DeleteEnvironmentRequest, + EncryptionConfig, + Environment, + EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, + GetEnvironmentRequest, + IPAllocationPolicy, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + LoadSnapshotRequest, + LoadSnapshotResponse, + MaintenanceWindow, + MasterAuthorizedNetworksConfig, + NetworkingConfig, + NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, + PrivateClusterConfig, + PrivateEnvironmentConfig, + RecoveryConfig, + SaveSnapshotRequest, + SaveSnapshotResponse, + ScheduledSnapshotsConfig, + SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, + UpdateEnvironmentRequest, + WebServerConfig, + WebServerNetworkAccessControl, + WorkloadsConfig, +) +from .image_versions import ( + ImageVersion, + ListImageVersionsRequest, + ListImageVersionsResponse, +) +from .operations import ( + OperationMetadata, +) + +__all__ = ( + 'CheckUpgradeResponse', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'UpdateEnvironmentRequest', + '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..30ee1fcd3a68 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py @@ -0,0 +1,2171 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'EnvironmentConfig', + 'WebServerNetworkAccessControl', + 'DatabaseConfig', + 'WebServerConfig', + 'EncryptionConfig', + 'MaintenanceWindow', + 'SoftwareConfig', + 'IPAllocationPolicy', + 'NodeConfig', + 'PrivateClusterConfig', + 'NetworkingConfig', + 'PrivateEnvironmentConfig', + 'WorkloadsConfig', + 'RecoveryConfig', + 'ScheduledSnapshotsConfig', + 'MasterAuthorizedNetworksConfig', + 'Environment', + '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_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 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_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. + """ + 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, + ) + + +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-*.*.*. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + + +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.*.*. + """ + + 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, + ) + + +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 + """ + + 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, + ) + + +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-*.*.*. + 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, + ) + 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. + """ + + 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, + ) + + 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, + ) + + +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 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. + """ + 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, + ) + + +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, + ) + + +__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..2bb874963b6c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..eefba0b0dc1c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..48efa670881b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/orchestration/airflow/service_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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..d0655bf2a8d1 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e0a9c90c110b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..8c36632bb46f --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6b3c921a3abd --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..ea715af765ad --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7563eeb487ad --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..19be15194623 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..cd333c7a0c19 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0de483668671 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..351c665a2dab --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a2534c3f26bb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..666b75a8df6a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..150ae0c0281a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0724fdb3ee19 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..953a0294dff3 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..9d3283833652 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a9943af88b29 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..de3a51afdf0b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c580bdd3f5c2 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..09882bf17a2a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..126036b5031c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..b7939eb741bc --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a0cbc7e8484f --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..902831c1966c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..84fb0d50f83d --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..7d5b6624afd5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..73f9b69284b1 --- /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,2076 @@ +{ + "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.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.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.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.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.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..a5e0a38cc890 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py @@ -0,0 +1,188 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', ), + 'database_failover': ('environment', ), + 'delete_environment': ('name', ), + 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), + 'fetch_database_properties': ('environment', ), + 'get_environment': ('name', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), + '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', ), + } + + 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..23b72c183665 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-orchestration-airflow' + + +description = "Google Cloud Orchestration Airflow API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/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..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..8741e5d4da57 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py @@ -0,0 +1,5935 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.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 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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 + + +@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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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, + ) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +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: + 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(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, + )) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +@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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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: + 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(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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch + 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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + # 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] + assert args[0] == environments.StopAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.StopAirflowCommandRequest() + + # 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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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.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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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: + 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(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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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: + 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(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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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" + + +@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 + pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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'] + + +@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 + pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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.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" + + +@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" + + +@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" + + +@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 + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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_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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).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 + + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() + 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', + '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.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_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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"): + 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"): + 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"): + 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, + 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..b63c0fe80da3 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py @@ -0,0 +1,2361 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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 +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 + + +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 + + +@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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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: + 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(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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch + 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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() + 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"): + 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"): + 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"): + 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, + 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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py new file mode 100644 index 000000000000..0de401396097 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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"2022, 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 = None + +# 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..04b6d7f74edb --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py @@ -0,0 +1,121 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 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 DeleteEnvironmentRequest +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 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 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 UpdateEnvironmentRequest +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', + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'RestartWebServerRequest', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'UpdateEnvironmentRequest', + '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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..d13501f77c55 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 CheckUpgradeRequest +from .types.environments import CheckUpgradeResponse +from .types.environments import CloudDataLineageIntegration +from .types.environments import CreateEnvironmentRequest +from .types.environments import DatabaseConfig +from .types.environments import DatabaseFailoverRequest +from .types.environments import DatabaseFailoverResponse +from .types.environments import DeleteEnvironmentRequest +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 IPAllocationPolicy +from .types.environments import ListEnvironmentsRequest +from .types.environments import ListEnvironmentsResponse +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 UpdateEnvironmentRequest +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', +'CheckUpgradeRequest', +'CheckUpgradeResponse', +'CloudDataLineageIntegration', +'CreateEnvironmentRequest', +'DatabaseConfig', +'DatabaseFailoverRequest', +'DatabaseFailoverResponse', +'DeleteEnvironmentRequest', +'EncryptionConfig', +'Environment', +'EnvironmentConfig', +'EnvironmentsClient', +'ExecuteAirflowCommandRequest', +'ExecuteAirflowCommandResponse', +'FetchDatabasePropertiesRequest', +'FetchDatabasePropertiesResponse', +'GetEnvironmentRequest', +'IPAllocationPolicy', +'ImageVersion', +'ImageVersionsClient', +'ListEnvironmentsRequest', +'ListEnvironmentsResponse', +'ListImageVersionsRequest', +'ListImageVersionsResponse', +'LoadSnapshotRequest', +'LoadSnapshotResponse', +'MaintenanceWindow', +'MasterAuthorizedNetworksConfig', +'NetworkingConfig', +'NodeConfig', +'OperationMetadata', +'PollAirflowCommandRequest', +'PollAirflowCommandResponse', +'PrivateClusterConfig', +'PrivateEnvironmentConfig', +'RecoveryConfig', +'RestartWebServerRequest', +'SaveSnapshotRequest', +'SaveSnapshotResponse', +'ScheduledSnapshotsConfig', +'SoftwareConfig', +'StopAirflowCommandRequest', +'StopAirflowCommandResponse', +'UpdateEnvironmentRequest', +'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..ba26cde2ff19 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json @@ -0,0 +1,272 @@ + { + "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" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "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" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EnvironmentsAsyncClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "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" + ] + } + } + }, + "rest": { + "libraryClient": "EnvironmentsClient", + "rpcs": { + "CheckUpgrade": { + "methods": [ + "check_upgrade" + ] + }, + "CreateEnvironment": { + "methods": [ + "create_environment" + ] + }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, + "DeleteEnvironment": { + "methods": [ + "delete_environment" + ] + }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, + "GetEnvironment": { + "methods": [ + "get_environment" + ] + }, + "ListEnvironments": { + "methods": [ + "list_environments" + ] + }, + "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" + ] + } + } + } + } + }, + "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..405b1cebcf15 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.1.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..e8e1c3845db5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..63bae46eaf47 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b1089a0cdd0f --- /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,1967 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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 + + DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT + + environment_path = staticmethod(EnvironmentsClient.environment_path) + parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 + + get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.create_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.get_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_environments, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = 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 = gapic_v1.method_async.wrap_method( + self._client._transport.delete_environment, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.RestartWebServerRequest(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.restart_web_server, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.CheckUpgradeRequest(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.check_upgrade, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.StopAirflowCommandRequest(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.stop_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.PollAirflowCommandRequest(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.poll_airflow_command, + 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(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.SaveSnapshotRequest(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.save_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.LoadSnapshotRequest(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.load_snapshot, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.DatabaseFailoverRequest(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.database_failover, + 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(( + ("environment", request.environment), + )), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, + 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(( + ("environment", request.environment), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..ce12e7f46593 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py @@ -0,0 +1,2181 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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 common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, EnvironmentsTransport): + # transport is a EnvironmentsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.CreateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.GetEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.ListEnvironmentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.UpdateEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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.') + + # Minor optimization to avoid making a copy if the user passes + # in a environments.DeleteEnvironmentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.RestartWebServerRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.CheckUpgradeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.ExecuteAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.StopAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.PollAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.SaveSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.LoadSnapshotRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.DatabaseFailoverRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.FetchDatabasePropertiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..1c973713f7ad --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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) 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..9384fe0b2c46 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..46cd89662ba6 --- /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,365 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.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.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 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..75d8cb291ca7 --- /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,686 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.longrunning import operations_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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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 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..4fa5e7096906 --- /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,685 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +from google.longrunning import operations_pb2 +from google.longrunning import operations_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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def 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 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 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..0c49b3fd1e45 --- /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,2036 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1beta1.types import environments +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_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_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_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_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 + + 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_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_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_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_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_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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_environment(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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_environment(resp) + return resp + + 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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 _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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_environment(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 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 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 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 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 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..c8beb58456d9 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..3374d08e134f --- /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,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.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 as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.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 +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 + + DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT + + 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 + + get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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.") + + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.list_image_versions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.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.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + async def __aenter__(self): + 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..2f3b5a6f46a3 --- /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,660 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.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] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # 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 +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") + + DEFAULT_ENDPOINT = "composer.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + 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): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageVersionsTransport): + # transport is a ImageVersionsTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_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.') + + # Minor optimization to avoid making a copy if the user passes + # in a image_versions.ListImageVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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), + )), + ) + + # 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),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Send the request. + rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + + + + + + + +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..3ae9fe2c0711 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..a11e27f277bb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..736c36ad0f7b --- /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,176 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_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..69f0488c287a --- /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,319 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +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[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = '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..3028a9bc9c05 --- /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,318 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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 +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`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'composer.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def 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 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..57c90e2340b2 --- /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,534 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions + +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. + 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'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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..f038e1722963 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ( + CheckUpgradeRequest, + CheckUpgradeResponse, + CloudDataLineageIntegration, + CreateEnvironmentRequest, + DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, + DeleteEnvironmentRequest, + EncryptionConfig, + Environment, + EnvironmentConfig, + ExecuteAirflowCommandRequest, + ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, + GetEnvironmentRequest, + IPAllocationPolicy, + ListEnvironmentsRequest, + ListEnvironmentsResponse, + LoadSnapshotRequest, + LoadSnapshotResponse, + MaintenanceWindow, + MasterAuthorizedNetworksConfig, + NetworkingConfig, + NodeConfig, + PollAirflowCommandRequest, + PollAirflowCommandResponse, + PrivateClusterConfig, + PrivateEnvironmentConfig, + RecoveryConfig, + RestartWebServerRequest, + SaveSnapshotRequest, + SaveSnapshotResponse, + ScheduledSnapshotsConfig, + SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, + UpdateEnvironmentRequest, + WebServerConfig, + WebServerNetworkAccessControl, + WorkloadsConfig, +) +from .image_versions import ( + ImageVersion, + ListImageVersionsRequest, + ListImageVersionsResponse, +) +from .operations import ( + OperationMetadata, +) + +__all__ = ( + 'CheckUpgradeRequest', + 'CheckUpgradeResponse', + 'CloudDataLineageIntegration', + 'CreateEnvironmentRequest', + 'DatabaseConfig', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'DeleteEnvironmentRequest', + 'EncryptionConfig', + 'Environment', + 'EnvironmentConfig', + 'ExecuteAirflowCommandRequest', + 'ExecuteAirflowCommandResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'GetEnvironmentRequest', + 'IPAllocationPolicy', + 'ListEnvironmentsRequest', + 'ListEnvironmentsResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'MaintenanceWindow', + 'MasterAuthorizedNetworksConfig', + 'NetworkingConfig', + 'NodeConfig', + 'PollAirflowCommandRequest', + 'PollAirflowCommandResponse', + 'PrivateClusterConfig', + 'PrivateEnvironmentConfig', + 'RecoveryConfig', + 'RestartWebServerRequest', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'ScheduledSnapshotsConfig', + 'SoftwareConfig', + 'StopAirflowCommandRequest', + 'StopAirflowCommandResponse', + 'UpdateEnvironmentRequest', + '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..ce99ecf7fc17 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py @@ -0,0 +1,2344 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', + 'SaveSnapshotRequest', + 'SaveSnapshotResponse', + 'LoadSnapshotRequest', + 'LoadSnapshotResponse', + 'DatabaseFailoverRequest', + 'DatabaseFailoverResponse', + 'FetchDatabasePropertiesRequest', + 'FetchDatabasePropertiesResponse', + 'EnvironmentConfig', + 'WebServerNetworkAccessControl', + 'SoftwareConfig', + 'IPAllocationPolicy', + 'NodeConfig', + 'PrivateClusterConfig', + 'NetworkingConfig', + 'PrivateEnvironmentConfig', + 'DatabaseConfig', + 'WebServerConfig', + 'EncryptionConfig', + 'MaintenanceWindow', + 'WorkloadsConfig', + '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 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, Cloud Composer + components may be subject to maintenance at any + time. + 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. + 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', + ) + 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. + """ + + 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', + ) + + +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 + """ + + 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, + ) + + +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-*.*.*. + 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, + ) + 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-*.*.*. + """ + + machine_type: str = proto.Field( + proto.STRING, + number=1, + ) + + +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. + """ + + 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, + ) + + 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, + ) + + +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. + """ + 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, + ) + + +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..df8c10475773 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..1c4f37959de4 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..f2e63423782c --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/orchestration/airflow/service_v1beta1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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..6f832b6fe4fa --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..25de62db95cb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..4e1a6142eb1c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..47af308b6b91 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..14bdd3bd816b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..468299ee386a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e0b793c36621 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..c89c8ed4e75a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..a651cba160a3 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d78b247ca3c5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..99693fbb4c54 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..fba72d5ea4df --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..bf32e05c79fc --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6472177609b7 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..1ab6ce68e4c3 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..56d6f268d9fb --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..9a689ea86069 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..6424bbd4ba94 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..1654e6e195b6 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..edefc8c82b64 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..2c26cfbc4c2b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..cd5f25d19a97 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..e007dcd0595a --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..88e01f01d51c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..d2923ae34a2c --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..354eeea59b65 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..a848381a9c06 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0de210f8e6d5 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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..3651597681c2 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..0b68eee82db0 --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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..fe40746345fa --- /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,2382 @@ +{ + "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.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.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.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.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.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..ec51364c3cad --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py @@ -0,0 +1,190 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', ), + 'database_failover': ('environment', ), + 'delete_environment': ('name', ), + 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), + 'fetch_database_properties': ('environment', ), + 'get_environment': ('name', ), + 'list_environments': ('parent', 'page_size', 'page_token', ), + 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), + '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', ), + } + + 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..050167f108da --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-orchestration-airflow-service' + + +description = "Google Cloud Orchestration Airflow Service API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/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..6c44adfea7ee --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt @@ -0,0 +1,9 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.0 +proto-plus==1.22.0 +protobuf==3.19.5 diff --git a/owl-bot-staging/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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..231bc125017b --- /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 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..11e00456b387 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py @@ -0,0 +1,6509 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.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 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert 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 + + +@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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(EnvironmentsClient)) +@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.CreateEnvironmentRequest() + + # 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, + ) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +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: + 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(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, + )) + 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] + assert args[0] == environments.GetEnvironmentRequest() + + # 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 + + +@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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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: + 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(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] + assert args[0] == environments.ListEnvironmentsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_environments(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch + 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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.UpdateEnvironmentRequest() + + # 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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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: + 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(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] + assert args[0] == environments.DeleteEnvironmentRequest() + + # 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] + assert args[0] == environments.RestartWebServerRequest() + + # 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: + 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(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] + assert args[0] == environments.RestartWebServerRequest() + + # 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] + assert args[0] == environments.CheckUpgradeRequest() + + # 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: + 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(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] + assert args[0] == environments.CheckUpgradeRequest() + + # 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] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.ExecuteAirflowCommandRequest() + + # 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] + assert args[0] == environments.StopAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.StopAirflowCommandRequest() + + # 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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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: + 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(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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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.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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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: + 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(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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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: + 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(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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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: + 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(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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and 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_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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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" + + +@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" + + +@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" + + +@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 + pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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'] + + +@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 + pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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.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" + + +@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" + + +@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" + + +@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 + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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_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, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).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 + + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() + 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', + '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.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_common_billing_account_path(): + billing_account = "cuttlefish" + 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": "mussel", + } + 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 = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = EnvironmentsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + 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 = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EnvironmentsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + 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 = "squid" + expected = "projects/{project}".format(project=project, ) + actual = EnvironmentsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + 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 = "whelk" + location = "octopus" + 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": "oyster", + "location": "nudibranch", + } + 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"): + 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"): + 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"): + 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, + 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..f6d496ae6a70 --- /dev/null +++ b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py @@ -0,0 +1,2361 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import 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 +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 + + +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 + + +@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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (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", modify_default_endpoint(ImageVersionsClient)) +@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + 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 + + +@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, + 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, + 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, + 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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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: + 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(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] + assert args[0] == image_versions.ListImageVersionsRequest() + + # 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, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_image_versions(request={}) + + assert pager._metadata == 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 = [] + async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch + 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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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' + + +@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 + pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() + 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"): + 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"): + 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"): + 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, + 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 d54c8cdfcb7a2548dd3ba321297f8a78a6a45581 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 13 Jun 2023 22:53:45 +0000 Subject: [PATCH 4/4] =?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/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 | 115 - .../airflow/service/gapic_version.py | 16 - .../orchestration/airflow/service/py.typed | 2 - .../airflow/service_v1/__init__.py | 116 - .../airflow/service_v1/gapic_metadata.json | 242 - .../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 | 1739 ----- .../services/environments/client.py | 1951 ----- .../services/environments/pagers.py | 139 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 337 - .../services/environments/transports/grpc.py | 631 -- .../environments/transports/grpc_asyncio.py | 630 -- .../services/environments/transports/rest.py | 1803 ----- .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 464 -- .../services/image_versions/client.py | 660 -- .../services/image_versions/pagers.py | 139 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 176 - .../image_versions/transports/grpc.py | 319 - .../image_versions/transports/grpc_asyncio.py | 318 - .../image_versions/transports/rest.py | 534 -- .../airflow/service_v1/types/__init__.py | 108 - .../airflow/service_v1/types/environments.py | 2171 ------ .../service_v1/types/image_versions.py | 148 - .../airflow/service_v1/types/operations.py | 147 - .../v1/mypy.ini | 3 - .../v1/noxfile.py | 184 - ...d_environments_create_environment_async.py | 55 - ...ed_environments_create_environment_sync.py | 55 - ...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 - ...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 - ...ed_environments_list_environments_async.py | 52 - ...ted_environments_list_environments_sync.py | 52 - ...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 - ...mage_versions_list_image_versions_async.py | 52 - ...image_versions_list_image_versions_sync.py | 52 - ...loud.orchestration.airflow.service.v1.json | 2076 ------ .../v1/scripts/fixup_service_v1_keywords.py | 188 - .../v1/setup.py | 90 - .../v1/testing/constraints-3.10.txt | 6 - .../v1/testing/constraints-3.11.txt | 6 - .../v1/testing/constraints-3.12.txt | 6 - .../v1/testing/constraints-3.7.txt | 9 - .../v1/testing/constraints-3.8.txt | 6 - .../v1/testing/constraints-3.9.txt | 6 - .../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 | 5935 --------------- .../gapic/service_v1/test_image_versions.py | 2361 ------ .../v1beta1/.coveragerc | 13 - .../v1beta1/.flake8 | 33 - .../v1beta1/MANIFEST.in | 2 - .../v1beta1/README.rst | 49 - .../v1beta1/docs/conf.py | 376 - .../v1beta1/docs/index.rst | 7 - .../docs/service_v1beta1/environments.rst | 10 - .../docs/service_v1beta1/image_versions.rst | 10 - .../v1beta1/docs/service_v1beta1/services.rst | 7 - .../v1beta1/docs/service_v1beta1/types.rst | 6 - .../orchestration/airflow/service/__init__.py | 121 - .../airflow/service/gapic_version.py | 16 - .../orchestration/airflow/service/py.typed | 2 - .../airflow/service_v1beta1/__init__.py | 122 - .../service_v1beta1/gapic_metadata.json | 272 - .../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 | 1967 ----- .../services/environments/client.py | 2181 ------ .../services/environments/pagers.py | 139 - .../environments/transports/__init__.py | 38 - .../services/environments/transports/base.py | 365 - .../services/environments/transports/grpc.py | 686 -- .../environments/transports/grpc_asyncio.py | 685 -- .../services/environments/transports/rest.py | 2036 ------ .../services/image_versions/__init__.py | 22 - .../services/image_versions/async_client.py | 464 -- .../services/image_versions/client.py | 660 -- .../services/image_versions/pagers.py | 139 - .../image_versions/transports/__init__.py | 38 - .../image_versions/transports/base.py | 176 - .../image_versions/transports/grpc.py | 319 - .../image_versions/transports/grpc_asyncio.py | 318 - .../image_versions/transports/rest.py | 534 -- .../airflow/service_v1beta1/types/__init__.py | 114 - .../service_v1beta1/types/environments.py | 2344 ------ .../service_v1beta1/types/image_versions.py | 148 - .../service_v1beta1/types/operations.py | 143 - .../v1beta1/mypy.ini | 3 - .../v1beta1/noxfile.py | 184 - ...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 - ...d_environments_delete_environment_async.py | 55 - ...ed_environments_delete_environment_sync.py | 55 - ...ated_environments_get_environment_async.py | 51 - ...rated_environments_get_environment_sync.py | 51 - ...ed_environments_list_environments_async.py | 52 - ...ted_environments_list_environments_sync.py | 52 - ...erated_environments_load_snapshot_async.py | 55 - ...nerated_environments_load_snapshot_sync.py | 55 - ...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 - ...d_environments_update_environment_async.py | 55 - ...ed_environments_update_environment_sync.py | 55 - ...mage_versions_list_image_versions_async.py | 52 - ...image_versions_list_image_versions_sync.py | 52 - ...orchestration.airflow.service.v1beta1.json | 2382 ------ .../scripts/fixup_service_v1beta1_keywords.py | 190 - .../v1beta1/setup.py | 90 - .../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 | 9 - .../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 | 6509 ----------------- .../service_v1beta1/test_image_versions.py | 2361 ------ .../airflow/service_v1beta1/__init__.py | 16 + .../service_v1beta1/gapic_metadata.json | 75 + .../services/environments/async_client.py | 424 ++ .../services/environments/client.py | 431 ++ .../services/environments/transports/base.py | 82 + .../services/environments/transports/grpc.py | 143 + .../environments/transports/grpc_asyncio.py | 145 + .../services/environments/transports/rest.py | 651 ++ .../airflow/service_v1beta1/types/__init__.py | 16 + .../service_v1beta1/types/environments.py | 247 + .../service_v1beta1/types/operations.py | 5 + ...ed_environments_database_failover_async.py | 0 ...ted_environments_database_failover_sync.py | 0 ...ironments_execute_airflow_command_async.py | 0 ...vironments_execute_airflow_command_sync.py | 0 ...onments_fetch_database_properties_async.py | 0 ...ronments_fetch_database_properties_sync.py | 0 ...environments_poll_airflow_command_async.py | 0 ..._environments_poll_airflow_command_sync.py | 0 ...environments_stop_airflow_command_async.py | 0 ..._environments_stop_airflow_command_sync.py | 0 ...orchestration.airflow.service.v1beta1.json | 1075 ++- .../scripts/fixup_service_v1beta1_keywords.py | 5 + .../service_v1beta1/test_environments.py | 3568 ++++++--- 184 files changed, 5741 insertions(+), 54552 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/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_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_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_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_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_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/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_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_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_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_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_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_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_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 rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py (100%) rename {owl-bot-staging/google-cloud-orchestration-airflow/v1beta1 => packages/google-cloud-orchestration-airflow}/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py (100%) 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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py deleted file mode 100644 index 55eb11f096a4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2022, 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 = None - -# 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 511c9ad31561..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service/__init__.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CreateEnvironmentRequest -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 DeleteEnvironmentRequest -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 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 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 UpdateEnvironmentRequest -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', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'UpdateEnvironmentRequest', - '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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 366523066689..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/__init__.py +++ /dev/null @@ -1,116 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CreateEnvironmentRequest -from .types.environments import DatabaseConfig -from .types.environments import DatabaseFailoverRequest -from .types.environments import DatabaseFailoverResponse -from .types.environments import DeleteEnvironmentRequest -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 IPAllocationPolicy -from .types.environments import ListEnvironmentsRequest -from .types.environments import ListEnvironmentsResponse -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 UpdateEnvironmentRequest -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', -'CreateEnvironmentRequest', -'DatabaseConfig', -'DatabaseFailoverRequest', -'DatabaseFailoverResponse', -'DeleteEnvironmentRequest', -'EncryptionConfig', -'Environment', -'EnvironmentConfig', -'EnvironmentsClient', -'ExecuteAirflowCommandRequest', -'ExecuteAirflowCommandResponse', -'FetchDatabasePropertiesRequest', -'FetchDatabasePropertiesResponse', -'GetEnvironmentRequest', -'IPAllocationPolicy', -'ImageVersion', -'ImageVersionsClient', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListImageVersionsRequest', -'ListImageVersionsResponse', -'LoadSnapshotRequest', -'LoadSnapshotResponse', -'MaintenanceWindow', -'MasterAuthorizedNetworksConfig', -'NetworkingConfig', -'NodeConfig', -'OperationMetadata', -'PollAirflowCommandRequest', -'PollAirflowCommandResponse', -'PrivateClusterConfig', -'PrivateEnvironmentConfig', -'RecoveryConfig', -'SaveSnapshotRequest', -'SaveSnapshotResponse', -'ScheduledSnapshotsConfig', -'SoftwareConfig', -'StopAirflowCommandRequest', -'StopAirflowCommandResponse', -'UpdateEnvironmentRequest', -'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 e35a8b09bf99..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/gapic_metadata.json +++ /dev/null @@ -1,242 +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" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - }, - "rest": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "LoadSnapshot": { - "methods": [ - "load_snapshot" - ] - }, - "PollAirflowCommand": { - "methods": [ - "poll_airflow_command" - ] - }, - "SaveSnapshot": { - "methods": [ - "save_snapshot" - ] - }, - "StopAirflowCommand": { - "methods": [ - "stop_airflow_command" - ] - }, - "UpdateEnvironment": { - "methods": [ - "update_environment" - ] - } - } - } - } - }, - "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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 e8e1c3845db5..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 63bae46eaf47..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 4b37a1ba9e0b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/async_client.py +++ /dev/null @@ -1,1739 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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 - - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - - environment_path = staticmethod(EnvironmentsClient.environment_path) - parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 - - get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.create_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_environments, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.StopAirflowCommandRequest(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.stop_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.PollAirflowCommandRequest(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.poll_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.SaveSnapshotRequest(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.save_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.LoadSnapshotRequest(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.load_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.DatabaseFailoverRequest(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.database_failover, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, - 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(( - ("environment", request.environment), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 09cc5463bf16..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/client.py +++ /dev/null @@ -1,1951 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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 common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.GetEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.ListEnvironmentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.DeleteEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.ExecuteAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.StopAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.PollAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.SaveSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.LoadSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.DatabaseFailoverRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.FetchDatabasePropertiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 61dda03258a4..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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) 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 9384fe0b2c46..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 51d0225f04d6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/base.py +++ /dev/null @@ -1,337 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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.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 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 48ad6fda5f55..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/grpc.py +++ /dev/null @@ -1,631 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 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 14cc807c075d..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,630 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.orchestration.airflow.service_v1.types import environments -from google.longrunning import operations_pb2 -from google.longrunning import operations_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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def 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 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 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 76cdeabf2fbf..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/environments/transports/rest.py +++ /dev/null @@ -1,1803 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1.types import environments -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_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_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_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_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 - - 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_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_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_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_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_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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_environment(resp) - return resp - - 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(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 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 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 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 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 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 c8beb58456d9..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 331abbfbda40..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,464 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.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 -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 - - DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - - 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 - - get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_image_versions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 5883379867ba..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/services/image_versions/client.py +++ /dev/null @@ -1,660 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ImageVersionsTransport): - # transport is a ImageVersionsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_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.') - - # Minor optimization to avoid making a copy if the user passes - # in a image_versions.ListImageVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 328e922af2cb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 a11e27f277bb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 8511a3e8d148..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,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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 fafc0ffbf30f..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,319 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 52c70b26d13d..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,318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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 -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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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 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 06cb8c005fc8..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,534 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1.types import image_versions - -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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 2fdc02aaa78b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/__init__.py +++ /dev/null @@ -1,108 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, - CreateEnvironmentRequest, - DatabaseConfig, - DatabaseFailoverRequest, - DatabaseFailoverResponse, - DeleteEnvironmentRequest, - EncryptionConfig, - Environment, - EnvironmentConfig, - ExecuteAirflowCommandRequest, - ExecuteAirflowCommandResponse, - FetchDatabasePropertiesRequest, - FetchDatabasePropertiesResponse, - GetEnvironmentRequest, - IPAllocationPolicy, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - LoadSnapshotRequest, - LoadSnapshotResponse, - MaintenanceWindow, - MasterAuthorizedNetworksConfig, - NetworkingConfig, - NodeConfig, - PollAirflowCommandRequest, - PollAirflowCommandResponse, - PrivateClusterConfig, - PrivateEnvironmentConfig, - RecoveryConfig, - SaveSnapshotRequest, - SaveSnapshotResponse, - ScheduledSnapshotsConfig, - SoftwareConfig, - StopAirflowCommandRequest, - StopAirflowCommandResponse, - UpdateEnvironmentRequest, - WebServerConfig, - WebServerNetworkAccessControl, - WorkloadsConfig, -) -from .image_versions import ( - ImageVersion, - ListImageVersionsRequest, - ListImageVersionsResponse, -) -from .operations import ( - OperationMetadata, -) - -__all__ = ( - 'CheckUpgradeResponse', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'UpdateEnvironmentRequest', - '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 30ee1fcd3a68..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/google/cloud/orchestration/airflow/service_v1/types/environments.py +++ /dev/null @@ -1,2171 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'EnvironmentConfig', - 'WebServerNetworkAccessControl', - 'DatabaseConfig', - 'WebServerConfig', - 'EncryptionConfig', - 'MaintenanceWindow', - 'SoftwareConfig', - 'IPAllocationPolicy', - 'NodeConfig', - 'PrivateClusterConfig', - 'NetworkingConfig', - 'PrivateEnvironmentConfig', - 'WorkloadsConfig', - 'RecoveryConfig', - 'ScheduledSnapshotsConfig', - 'MasterAuthorizedNetworksConfig', - 'Environment', - '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_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 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_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. - """ - 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, - ) - - -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-*.*.*. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - - -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.*.*. - """ - - 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, - ) - - -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 - """ - - 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, - ) - - -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-*.*.*. - 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, - ) - 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. - """ - - 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, - ) - - 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, - ) - - -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 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. - """ - 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, - ) - - -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, - ) - - -__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 2bb874963b6c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 eefba0b0dc1c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 48efa670881b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/orchestration/airflow/service_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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 d0655bf2a8d1..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 e0a9c90c110b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 8c36632bb46f..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 6b3c921a3abd..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 ea715af765ad..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 7563eeb487ad..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 19be15194623..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 cd333c7a0c19..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0de483668671..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 351c665a2dab..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 a2534c3f26bb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 666b75a8df6a..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 150ae0c0281a..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0724fdb3ee19..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 953a0294dff3..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 9d3283833652..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 a9943af88b29..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 de3a51afdf0b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 c580bdd3f5c2..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 09882bf17a2a..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 126036b5031c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 b7939eb741bc..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 a0cbc7e8484f..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 902831c1966c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 84fb0d50f83d..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 7d5b6624afd5..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 73f9b69284b1..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,2076 +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.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.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.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.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.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 a5e0a38cc890..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/scripts/fixup_service_v1_keywords.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', ), - 'database_failover': ('environment', ), - 'delete_environment': ('name', ), - 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), - 'fetch_database_properties': ('environment', ), - 'get_environment': ('name', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), - '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', ), - } - - 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 23b72c183665..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-orchestration-airflow' - - -description = "Google Cloud Orchestration Airflow API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/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 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +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.0 -proto-plus==1.22.0 -protobuf==3.19.5 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 8741e5d4da57..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_environments.py +++ /dev/null @@ -1,5935 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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 -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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 - - -@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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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, - ) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -@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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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: - 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(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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch - 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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - # 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] - assert args[0] == environments.StopAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.StopAirflowCommandRequest() - - # 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] - assert args[0] == environments.PollAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.PollAirflowCommandRequest() - - # 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.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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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] - assert args[0] == environments.DatabaseFailoverRequest() - - # 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: - 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(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] - assert args[0] == environments.DatabaseFailoverRequest() - - # 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] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - # 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: - 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(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] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - # 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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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" - - -@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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" - - -@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_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}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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" - - -@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 - pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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'] - - -@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 - pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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.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" - - -@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" - - -@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" - - -@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 - pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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_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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).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 - - pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() - 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', - '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.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_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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"): - 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"): - 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"): - 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, - 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 b63c0fe80da3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1/tests/unit/gapic/service_v1/test_image_versions.py +++ /dev/null @@ -1,2361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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 -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 - - -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 - - -@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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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: - 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(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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch - 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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() - 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"): - 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"): - 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"): - 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, - 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/conf.py b/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py deleted file mode 100644 index 0de401396097..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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"2022, 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 = None - -# 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 04b6d7f74edb..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service/__init__.py +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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 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 DeleteEnvironmentRequest -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 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 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 UpdateEnvironmentRequest -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', - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'RestartWebServerRequest', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'UpdateEnvironmentRequest', - '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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 d13501f77c55..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/__init__.py +++ /dev/null @@ -1,122 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 CheckUpgradeRequest -from .types.environments import CheckUpgradeResponse -from .types.environments import CloudDataLineageIntegration -from .types.environments import CreateEnvironmentRequest -from .types.environments import DatabaseConfig -from .types.environments import DatabaseFailoverRequest -from .types.environments import DatabaseFailoverResponse -from .types.environments import DeleteEnvironmentRequest -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 IPAllocationPolicy -from .types.environments import ListEnvironmentsRequest -from .types.environments import ListEnvironmentsResponse -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 UpdateEnvironmentRequest -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', -'CheckUpgradeRequest', -'CheckUpgradeResponse', -'CloudDataLineageIntegration', -'CreateEnvironmentRequest', -'DatabaseConfig', -'DatabaseFailoverRequest', -'DatabaseFailoverResponse', -'DeleteEnvironmentRequest', -'EncryptionConfig', -'Environment', -'EnvironmentConfig', -'EnvironmentsClient', -'ExecuteAirflowCommandRequest', -'ExecuteAirflowCommandResponse', -'FetchDatabasePropertiesRequest', -'FetchDatabasePropertiesResponse', -'GetEnvironmentRequest', -'IPAllocationPolicy', -'ImageVersion', -'ImageVersionsClient', -'ListEnvironmentsRequest', -'ListEnvironmentsResponse', -'ListImageVersionsRequest', -'ListImageVersionsResponse', -'LoadSnapshotRequest', -'LoadSnapshotResponse', -'MaintenanceWindow', -'MasterAuthorizedNetworksConfig', -'NetworkingConfig', -'NodeConfig', -'OperationMetadata', -'PollAirflowCommandRequest', -'PollAirflowCommandResponse', -'PrivateClusterConfig', -'PrivateEnvironmentConfig', -'RecoveryConfig', -'RestartWebServerRequest', -'SaveSnapshotRequest', -'SaveSnapshotResponse', -'ScheduledSnapshotsConfig', -'SoftwareConfig', -'StopAirflowCommandRequest', -'StopAirflowCommandResponse', -'UpdateEnvironmentRequest', -'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 ba26cde2ff19..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json +++ /dev/null @@ -1,272 +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" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "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" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EnvironmentsAsyncClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "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" - ] - } - } - }, - "rest": { - "libraryClient": "EnvironmentsClient", - "rpcs": { - "CheckUpgrade": { - "methods": [ - "check_upgrade" - ] - }, - "CreateEnvironment": { - "methods": [ - "create_environment" - ] - }, - "DatabaseFailover": { - "methods": [ - "database_failover" - ] - }, - "DeleteEnvironment": { - "methods": [ - "delete_environment" - ] - }, - "ExecuteAirflowCommand": { - "methods": [ - "execute_airflow_command" - ] - }, - "FetchDatabaseProperties": { - "methods": [ - "fetch_database_properties" - ] - }, - "GetEnvironment": { - "methods": [ - "get_environment" - ] - }, - "ListEnvironments": { - "methods": [ - "list_environments" - ] - }, - "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" - ] - } - } - } - } - }, - "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 405b1cebcf15..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.1.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 e8e1c3845db5..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 63bae46eaf47..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b1089a0cdd0f..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py +++ /dev/null @@ -1,1967 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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 - - DEFAULT_ENDPOINT = EnvironmentsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EnvironmentsClient.DEFAULT_MTLS_ENDPOINT - - environment_path = staticmethod(EnvironmentsClient.environment_path) - parse_environment_path = staticmethod(EnvironmentsClient.parse_environment_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 - - get_transport_class = functools.partial(type(EnvironmentsClient).get_transport_class, type(EnvironmentsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, EnvironmentsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.create_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.get_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_environments, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = 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 = gapic_v1.method_async.wrap_method( - self._client._transport.delete_environment, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.RestartWebServerRequest(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.restart_web_server, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.CheckUpgradeRequest(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.check_upgrade, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.StopAirflowCommandRequest(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.stop_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.PollAirflowCommandRequest(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.poll_airflow_command, - 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(( - ("environment", request.environment), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.SaveSnapshotRequest(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.save_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.LoadSnapshotRequest(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.load_snapshot, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.DatabaseFailoverRequest(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.database_failover, - 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(( - ("environment", request.environment), - )), - ) - - # 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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. - request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, - 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(( - ("environment", request.environment), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_operations( - self, - request: Optional[operations_pb2.ListOperationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.ListOperationsResponse: - r"""Lists operations that match the specified filter in the request. - - Args: - request (:class:`~.operations_pb2.ListOperationsRequest`): - The request object. Request message for - `ListOperations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 ce12e7f46593..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py +++ /dev/null @@ -1,2181 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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 common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, EnvironmentsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, EnvironmentsTransport): - # transport is a EnvironmentsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.CreateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.GetEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.ListEnvironmentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.UpdateEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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.') - - # Minor optimization to avoid making a copy if the user passes - # in a environments.DeleteEnvironmentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.RestartWebServerRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.CheckUpgradeRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.ExecuteAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.StopAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.PollAirflowCommandRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.SaveSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.LoadSnapshotRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.DatabaseFailoverRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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. - # Minor optimization to avoid making a copy if the user passes - # in a environments.FetchDatabasePropertiesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 1c973713f7ad..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/pagers.py +++ /dev/null @@ -1,139 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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) 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 9384fe0b2c46..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 46cd89662ba6..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py +++ /dev/null @@ -1,365 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.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.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 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 75d8cb291ca7..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py +++ /dev/null @@ -1,686 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -from google.longrunning import operations_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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 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 4fa5e7096906..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,685 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -from google.longrunning import operations_pb2 -from google.longrunning import operations_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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def 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 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 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 0c49b3fd1e45..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py +++ /dev/null @@ -1,2036 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1beta1.types import environments -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_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_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_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_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 - - 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_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_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_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_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_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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_environment(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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_environment(resp) - return resp - - 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 _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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_environment(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 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 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 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 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 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 c8beb58456d9..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 3374d08e134f..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,464 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.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 as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.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 -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 - - DEFAULT_ENDPOINT = ImageVersionsClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ImageVersionsClient.DEFAULT_MTLS_ENDPOINT - - 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 - - get_transport_class = functools.partial(type(ImageVersionsClient).get_transport_class, type(ImageVersionsClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ImageVersionsTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = 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 (Union[str, ~.ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = 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.Retry): Designation of what errors, if any, - should be retried. - timeout (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.") - - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.list_image_versions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.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.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.ListOperationsResponse: - Response message for ``ListOperations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.ListOperationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.list_operations, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - async def __aenter__(self): - 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 2f3b5a6f46a3..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/services/image_versions/client.py +++ /dev/null @@ -1,660 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.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] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # 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 -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") - - DEFAULT_ENDPOINT = "composer.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - 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): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, 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 (Union[str, ImageVersionsTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ImageVersionsTransport): - # transport is a ImageVersionsTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_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.') - - # Minor optimization to avoid making a copy if the user passes - # in a image_versions.ListImageVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - 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), - )), - ) - - # 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),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_operation( - self, - request: Optional[operations_pb2.DeleteOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a long-running operation. - - This method indicates that the client is no longer interested - in the operation result. It does not cancel the operation. - If the server doesn't support this method, it returns - `google.rpc.Code.UNIMPLEMENTED`. - - Args: - request (:class:`~.operations_pb2.DeleteOperationRequest`): - The request object. Request message for - `DeleteOperation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - None - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.DeleteOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_operation, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - - - - - - - -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 3ae9fe2c0711..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 a11e27f277bb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 736c36ad0f7b..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,176 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_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 69f0488c287a..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,319 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -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[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = '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 3028a9bc9c05..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,318 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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 -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`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'composer.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def 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 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 57c90e2340b2..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,534 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.orchestration.airflow.service_v1beta1.types import image_versions - -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. - 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'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = 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 f038e1722963..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/__init__.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ( - CheckUpgradeRequest, - CheckUpgradeResponse, - CloudDataLineageIntegration, - CreateEnvironmentRequest, - DatabaseConfig, - DatabaseFailoverRequest, - DatabaseFailoverResponse, - DeleteEnvironmentRequest, - EncryptionConfig, - Environment, - EnvironmentConfig, - ExecuteAirflowCommandRequest, - ExecuteAirflowCommandResponse, - FetchDatabasePropertiesRequest, - FetchDatabasePropertiesResponse, - GetEnvironmentRequest, - IPAllocationPolicy, - ListEnvironmentsRequest, - ListEnvironmentsResponse, - LoadSnapshotRequest, - LoadSnapshotResponse, - MaintenanceWindow, - MasterAuthorizedNetworksConfig, - NetworkingConfig, - NodeConfig, - PollAirflowCommandRequest, - PollAirflowCommandResponse, - PrivateClusterConfig, - PrivateEnvironmentConfig, - RecoveryConfig, - RestartWebServerRequest, - SaveSnapshotRequest, - SaveSnapshotResponse, - ScheduledSnapshotsConfig, - SoftwareConfig, - StopAirflowCommandRequest, - StopAirflowCommandResponse, - UpdateEnvironmentRequest, - WebServerConfig, - WebServerNetworkAccessControl, - WorkloadsConfig, -) -from .image_versions import ( - ImageVersion, - ListImageVersionsRequest, - ListImageVersionsResponse, -) -from .operations import ( - OperationMetadata, -) - -__all__ = ( - 'CheckUpgradeRequest', - 'CheckUpgradeResponse', - 'CloudDataLineageIntegration', - 'CreateEnvironmentRequest', - 'DatabaseConfig', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'DeleteEnvironmentRequest', - 'EncryptionConfig', - 'Environment', - 'EnvironmentConfig', - 'ExecuteAirflowCommandRequest', - 'ExecuteAirflowCommandResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'GetEnvironmentRequest', - 'IPAllocationPolicy', - 'ListEnvironmentsRequest', - 'ListEnvironmentsResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'MaintenanceWindow', - 'MasterAuthorizedNetworksConfig', - 'NetworkingConfig', - 'NodeConfig', - 'PollAirflowCommandRequest', - 'PollAirflowCommandResponse', - 'PrivateClusterConfig', - 'PrivateEnvironmentConfig', - 'RecoveryConfig', - 'RestartWebServerRequest', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'ScheduledSnapshotsConfig', - 'SoftwareConfig', - 'StopAirflowCommandRequest', - 'StopAirflowCommandResponse', - 'UpdateEnvironmentRequest', - '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 ce99ecf7fc17..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/google/cloud/orchestration/airflow/service_v1beta1/types/environments.py +++ /dev/null @@ -1,2344 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', - 'SaveSnapshotRequest', - 'SaveSnapshotResponse', - 'LoadSnapshotRequest', - 'LoadSnapshotResponse', - 'DatabaseFailoverRequest', - 'DatabaseFailoverResponse', - 'FetchDatabasePropertiesRequest', - 'FetchDatabasePropertiesResponse', - 'EnvironmentConfig', - 'WebServerNetworkAccessControl', - 'SoftwareConfig', - 'IPAllocationPolicy', - 'NodeConfig', - 'PrivateClusterConfig', - 'NetworkingConfig', - 'PrivateEnvironmentConfig', - 'DatabaseConfig', - 'WebServerConfig', - 'EncryptionConfig', - 'MaintenanceWindow', - 'WorkloadsConfig', - '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 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, Cloud Composer - components may be subject to maintenance at any - time. - 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. - 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', - ) - 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. - """ - - 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', - ) - - -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 - """ - - 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, - ) - - -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-*.*.*. - 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, - ) - 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-*.*.*. - """ - - machine_type: str = proto.Field( - proto.STRING, - number=1, - ) - - -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. - """ - - 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, - ) - - 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, - ) - - -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. - """ - 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, - ) - - -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 df8c10475773..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 1c4f37959de4..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 f2e63423782c..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/orchestration/airflow/service_v1beta1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/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 6f832b6fe4fa..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 25de62db95cb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 4e1a6142eb1c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 47af308b6b91..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 e0b793c36621..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 c89c8ed4e75a..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 bf32e05c79fc..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 6472177609b7..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 1ab6ce68e4c3..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 56d6f268d9fb..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 9a689ea86069..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 6424bbd4ba94..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 2c26cfbc4c2b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 cd5f25d19a97..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 e007dcd0595a..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 88e01f01d51c..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 a848381a9c06..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0de210f8e6d5..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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_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 3651597681c2..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 0b68eee82db0..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 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 fe40746345fa..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,2382 +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.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.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.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.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.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 ec51364c3cad..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/scripts/fixup_service_v1beta1_keywords.py +++ /dev/null @@ -1,190 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', ), - 'database_failover': ('environment', ), - 'delete_environment': ('name', ), - 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), - 'fetch_database_properties': ('environment', ), - 'get_environment': ('name', ), - 'list_environments': ('parent', 'page_size', 'page_token', ), - 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), - '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', ), - } - - 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 050167f108da..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/setup.py +++ /dev/null @@ -1,90 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-orchestration-airflow-service' - - -description = "Google Cloud Orchestration Airflow Service API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/orchestration/airflow/service/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - "proto-plus >= 1.22.0, <2.0.0dev", - "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", - "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", -] -url = "https://github.com/googleapis/python-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.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud", "google.cloud.orchestration", "google.cloud.orchestration.airflow"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/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 6c44adfea7ee..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/testing/constraints-3.7.txt +++ /dev/null @@ -1,9 +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.0 -proto-plus==1.22.0 -protobuf==3.19.5 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 231bc125017b..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 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 11e00456b387..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_environments.py +++ /dev/null @@ -1,6509 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.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 -from google.oauth2 import service_account -from google.protobuf import empty_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert 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 - - -@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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(EnvironmentsClient)) -@mock.patch.object(EnvironmentsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.CreateEnvironmentRequest() - - # 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, - ) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -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: - 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(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, - )) - 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] - assert args[0] == environments.GetEnvironmentRequest() - - # 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 - - -@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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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: - 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(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] - assert args[0] == environments.ListEnvironmentsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_environments(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_environments(request={})).pages: # pragma: no branch - 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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.UpdateEnvironmentRequest() - - # 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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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: - 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(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] - assert args[0] == environments.DeleteEnvironmentRequest() - - # 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] - assert args[0] == environments.RestartWebServerRequest() - - # 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: - 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(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] - assert args[0] == environments.RestartWebServerRequest() - - # 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] - assert args[0] == environments.CheckUpgradeRequest() - - # 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: - 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(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] - assert args[0] == environments.CheckUpgradeRequest() - - # 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] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.ExecuteAirflowCommandRequest() - - # 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] - assert args[0] == environments.StopAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.StopAirflowCommandRequest() - - # 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] - assert args[0] == environments.PollAirflowCommandRequest() - - # 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: - 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(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] - assert args[0] == environments.PollAirflowCommandRequest() - - # 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.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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.SaveSnapshotRequest() - - # 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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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: - 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(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] - assert args[0] == environments.LoadSnapshotRequest() - - # 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] - assert args[0] == environments.DatabaseFailoverRequest() - - # 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: - 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(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] - assert args[0] == environments.DatabaseFailoverRequest() - - # 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] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - # 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: - 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(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] - assert args[0] == environments.FetchDatabasePropertiesRequest() - - # 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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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" - - -@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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and 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_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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_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_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}}, '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}, 'private_environment_config': {'enable_private_environment': 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'}, '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}}, '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'}}, 'resilience_mode': 1}, 'uuid': 'uuid_value', 'state': 1, 'create_time': {}, 'update_time': {}, 'labels': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest 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" - - -@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" - - -@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" - - -@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 - pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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'] - - -@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 - pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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.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" - - -@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" - - -@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" - - -@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 - pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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_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, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).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 - - pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() - 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', - '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.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_common_billing_account_path(): - billing_account = "cuttlefish" - 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": "mussel", - } - 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 = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = EnvironmentsClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - 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 = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EnvironmentsClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - 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 = "squid" - expected = "projects/{project}".format(project=project, ) - actual = EnvironmentsClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - 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 = "whelk" - location = "octopus" - 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": "oyster", - "location": "nudibranch", - } - 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"): - 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"): - 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"): - 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, - 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 f6d496ae6a70..000000000000 --- a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/tests/unit/gapic/service_v1beta1/test_image_versions.py +++ /dev/null @@ -1,2361 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2022 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import 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 -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 - - -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 - - -@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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (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", modify_default_endpoint(ImageVersionsClient)) -@mock.patch.object(ImageVersionsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(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 - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - 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 - - -@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, - 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, - 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, - 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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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: - 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(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] - assert args[0] == image_versions.ListImageVersionsRequest() - - # 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, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_image_versions(request={}) - - assert pager._metadata == 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 = [] - async for page_ in (await client.list_image_versions(request={})).pages: # pragma: no branch - 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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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' - - -@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 - pb_return_value = image_versions.ListImageVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 = mock.Mock() - 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"): - 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"): - 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"): - 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, - 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_v1beta1/__init__.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/__init__.py index ce61a11a0527..98b7a1313935 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 @@ -28,11 +28,16 @@ CloudDataLineageIntegration, CreateEnvironmentRequest, DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, DeleteEnvironmentRequest, EncryptionConfig, Environment, EnvironmentConfig, + ExecuteAirflowCommandRequest, ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, GetEnvironmentRequest, IPAllocationPolicy, ListEnvironmentsRequest, @@ -43,6 +48,7 @@ MasterAuthorizedNetworksConfig, NetworkingConfig, NodeConfig, + PollAirflowCommandRequest, PollAirflowCommandResponse, PrivateClusterConfig, PrivateEnvironmentConfig, @@ -52,6 +58,8 @@ SaveSnapshotResponse, ScheduledSnapshotsConfig, SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, UpdateEnvironmentRequest, WebServerConfig, WebServerNetworkAccessControl, @@ -72,12 +80,17 @@ "CloudDataLineageIntegration", "CreateEnvironmentRequest", "DatabaseConfig", + "DatabaseFailoverRequest", + "DatabaseFailoverResponse", "DeleteEnvironmentRequest", "EncryptionConfig", "Environment", "EnvironmentConfig", "EnvironmentsClient", + "ExecuteAirflowCommandRequest", "ExecuteAirflowCommandResponse", + "FetchDatabasePropertiesRequest", + "FetchDatabasePropertiesResponse", "GetEnvironmentRequest", "IPAllocationPolicy", "ImageVersion", @@ -93,6 +106,7 @@ "NetworkingConfig", "NodeConfig", "OperationMetadata", + "PollAirflowCommandRequest", "PollAirflowCommandResponse", "PrivateClusterConfig", "PrivateEnvironmentConfig", @@ -102,6 +116,8 @@ "SaveSnapshotResponse", "ScheduledSnapshotsConfig", "SoftwareConfig", + "StopAirflowCommandRequest", + "StopAirflowCommandResponse", "UpdateEnvironmentRequest", "WebServerConfig", "WebServerNetworkAccessControl", diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json index 1f120bab3d17..ba26cde2ff19 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/gapic_metadata.json @@ -20,11 +20,26 @@ "create_environment" ] }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, "DeleteEnvironment": { "methods": [ "delete_environment" ] }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, "GetEnvironment": { "methods": [ "get_environment" @@ -40,6 +55,11 @@ "load_snapshot" ] }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, "RestartWebServer": { "methods": [ "restart_web_server" @@ -50,6 +70,11 @@ "save_snapshot" ] }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" @@ -70,11 +95,26 @@ "create_environment" ] }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, "DeleteEnvironment": { "methods": [ "delete_environment" ] }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, "GetEnvironment": { "methods": [ "get_environment" @@ -90,6 +130,11 @@ "load_snapshot" ] }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, "RestartWebServer": { "methods": [ "restart_web_server" @@ -100,6 +145,11 @@ "save_snapshot" ] }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" @@ -120,11 +170,26 @@ "create_environment" ] }, + "DatabaseFailover": { + "methods": [ + "database_failover" + ] + }, "DeleteEnvironment": { "methods": [ "delete_environment" ] }, + "ExecuteAirflowCommand": { + "methods": [ + "execute_airflow_command" + ] + }, + "FetchDatabaseProperties": { + "methods": [ + "fetch_database_properties" + ] + }, "GetEnvironment": { "methods": [ "get_environment" @@ -140,6 +205,11 @@ "load_snapshot" ] }, + "PollAirflowCommand": { + "methods": [ + "poll_airflow_command" + ] + }, "RestartWebServer": { "methods": [ "restart_web_server" @@ -150,6 +220,11 @@ "save_snapshot" ] }, + "StopAirflowCommand": { + "methods": [ + "stop_airflow_command" + ] + }, "UpdateEnvironment": { "methods": [ "update_environment" diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py index ab0736d07235..09cc9dabb09b 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/async_client.py @@ -1227,6 +1227,248 @@ async def sample_check_upgrade(): # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.ExecuteAirflowCommandRequest(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.execute_airflow_command, + 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( + (("environment", request.environment),) + ), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.StopAirflowCommandRequest(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.stop_airflow_command, + 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( + (("environment", request.environment),) + ), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.PollAirflowCommandRequest(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.poll_airflow_command, + 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( + (("environment", request.environment),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def save_snapshot( self, request: Optional[Union[environments.SaveSnapshotRequest, dict]] = None, @@ -1425,6 +1667,188 @@ async def sample_load_snapshot(): # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.DatabaseFailoverRequest(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.database_failover, + 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( + (("environment", request.environment),) + ), + ) + + # 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.Retry): Designation of what errors, if any, + should be retried. + timeout (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. + request = environments.FetchDatabasePropertiesRequest(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.fetch_database_properties, + 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( + (("environment", request.environment),) + ), + ) + + # 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, diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py index 482c06af5ee3..5dd4bfc6692d 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/client.py @@ -1462,6 +1462,251 @@ def sample_check_upgrade(): # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.ExecuteAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.StopAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.PollAirflowCommandRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def save_snapshot( self, request: Optional[Union[environments.SaveSnapshotRequest, dict]] = None, @@ -1662,6 +1907,192 @@ def sample_load_snapshot(): # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.DatabaseFailoverRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # 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. + # Minor optimization to avoid making a copy if the user passes + # in a environments.FetchDatabasePropertiesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + 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),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "EnvironmentsClient": return self diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py index 7b7527cdde77..5dc12fdec60d 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/base.py @@ -160,6 +160,21 @@ def _prep_wrapped_messages(self, client_info): 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.save_snapshot: gapic_v1.method.wrap_method( self.save_snapshot, default_timeout=None, @@ -170,6 +185,16 @@ def _prep_wrapped_messages(self, client_info): 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): @@ -252,6 +277,42 @@ def check_upgrade( ]: 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 save_snapshot( self, @@ -270,6 +331,27 @@ def load_snapshot( ]: 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, diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py index 0ed8ffd24831..75c253dc8fe2 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc.py @@ -431,6 +431,93 @@ def check_upgrade( ) 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 save_snapshot( self, @@ -489,6 +576,62 @@ def load_snapshot( ) 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() diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py index 5ff5ff163f77..ad2ff852cf07 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/grpc_asyncio.py @@ -449,6 +449,93 @@ def check_upgrade( ) 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 save_snapshot( self, @@ -511,6 +598,64 @@ def load_snapshot( ) 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 close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py index 85315d7ca568..2ff9d1dc1894 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/services/environments/transports/rest.py @@ -88,6 +88,14 @@ def post_create_environment(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 @@ -96,6 +104,22 @@ def post_delete_environment(self, response): logging.log(f"Received response: {response}") return response + 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 @@ -120,6 +144,14 @@ 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 @@ -136,6 +168,14 @@ 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 @@ -196,6 +236,29 @@ def post_create_environment( """ 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, @@ -219,6 +282,52 @@ def post_delete_environment( """ return response + 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, @@ -288,6 +397,29 @@ def post_load_snapshot( """ 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, @@ -334,6 +466,29 @@ def post_save_snapshot( """ 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, @@ -741,6 +896,95 @@ def __call__( resp = self._interceptor.post_create_environment(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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_database_failover(resp) + return resp + class _DeleteEnvironment(EnvironmentsRestStub): def __hash__(self): return hash("DeleteEnvironment") @@ -819,6 +1063,185 @@ def __call__( resp = self._interceptor.post_delete_environment(resp) return resp + 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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") @@ -1062,6 +1485,94 @@ def __call__( 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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") @@ -1235,6 +1746,94 @@ def __call__( 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"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = 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") @@ -1351,6 +1950,14 @@ def create_environment( # In C++ this would require a dynamic_cast return self._CreateEnvironment(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, @@ -1359,6 +1966,28 @@ def delete_environment( # In C++ this would require a dynamic_cast return self._DeleteEnvironment(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, @@ -1385,6 +2014,17 @@ def load_snapshot( # 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, @@ -1401,6 +2041,17 @@ def save_snapshot( # 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, 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 d23643d198fd..673619aa0e2c 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 @@ -19,11 +19,16 @@ CloudDataLineageIntegration, CreateEnvironmentRequest, DatabaseConfig, + DatabaseFailoverRequest, + DatabaseFailoverResponse, DeleteEnvironmentRequest, EncryptionConfig, Environment, EnvironmentConfig, + ExecuteAirflowCommandRequest, ExecuteAirflowCommandResponse, + FetchDatabasePropertiesRequest, + FetchDatabasePropertiesResponse, GetEnvironmentRequest, IPAllocationPolicy, ListEnvironmentsRequest, @@ -34,6 +39,7 @@ MasterAuthorizedNetworksConfig, NetworkingConfig, NodeConfig, + PollAirflowCommandRequest, PollAirflowCommandResponse, PrivateClusterConfig, PrivateEnvironmentConfig, @@ -43,6 +49,8 @@ SaveSnapshotResponse, ScheduledSnapshotsConfig, SoftwareConfig, + StopAirflowCommandRequest, + StopAirflowCommandResponse, UpdateEnvironmentRequest, WebServerConfig, WebServerNetworkAccessControl, @@ -61,11 +69,16 @@ "CloudDataLineageIntegration", "CreateEnvironmentRequest", "DatabaseConfig", + "DatabaseFailoverRequest", + "DatabaseFailoverResponse", "DeleteEnvironmentRequest", "EncryptionConfig", "Environment", "EnvironmentConfig", + "ExecuteAirflowCommandRequest", "ExecuteAirflowCommandResponse", + "FetchDatabasePropertiesRequest", + "FetchDatabasePropertiesResponse", "GetEnvironmentRequest", "IPAllocationPolicy", "ListEnvironmentsRequest", @@ -76,6 +89,7 @@ "MasterAuthorizedNetworksConfig", "NetworkingConfig", "NodeConfig", + "PollAirflowCommandRequest", "PollAirflowCommandResponse", "PrivateClusterConfig", "PrivateEnvironmentConfig", @@ -85,6 +99,8 @@ "SaveSnapshotResponse", "ScheduledSnapshotsConfig", "SoftwareConfig", + "StopAirflowCommandRequest", + "StopAirflowCommandResponse", "UpdateEnvironmentRequest", "WebServerConfig", "WebServerNetworkAccessControl", 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 1ee53c290b37..c7dfc4511123 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 @@ -31,12 +31,20 @@ "DeleteEnvironmentRequest", "UpdateEnvironmentRequest", "RestartWebServerRequest", + "ExecuteAirflowCommandRequest", "ExecuteAirflowCommandResponse", + "StopAirflowCommandRequest", + "StopAirflowCommandResponse", + "PollAirflowCommandRequest", "PollAirflowCommandResponse", "SaveSnapshotRequest", "SaveSnapshotResponse", "LoadSnapshotRequest", "LoadSnapshotResponse", + "DatabaseFailoverRequest", + "DatabaseFailoverResponse", + "FetchDatabasePropertiesRequest", + "FetchDatabasePropertiesResponse", "EnvironmentConfig", "WebServerNetworkAccessControl", "SoftwareConfig", @@ -419,6 +427,44 @@ class RestartWebServerRequest(proto.Message): ) +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. @@ -454,6 +500,114 @@ class ExecuteAirflowCommandResponse(proto.Message): ) +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. @@ -620,6 +774,75 @@ 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. @@ -725,6 +948,11 @@ class EnvironmentConfig(proto.Message): This field is supported for Cloud Composer environments in versions composer-2.\ *.*-airflow-*.*.\* and newer. + 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): @@ -745,6 +973,20 @@ class EnvironmentSize(proto.Enum): 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, @@ -825,6 +1067,11 @@ class EnvironmentSize(proto.Enum): number=18, message="RecoveryConfig", ) + resilience_mode: ResilienceMode = proto.Field( + proto.ENUM, + number=20, + enum=ResilienceMode, + ) class WebServerNetworkAccessControl(proto.Message): diff --git a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py index 7f7922e24dc3..08c8ed2a247b 100644 --- a/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py +++ b/packages/google-cloud-orchestration-airflow/google/cloud/orchestration/airflow/service_v1beta1/types/operations.py @@ -95,6 +95,10 @@ class Type(proto.Enum): 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 @@ -103,6 +107,7 @@ class Type(proto.Enum): CHECK = 4 SAVE_SNAPSHOT = 5 LOAD_SNAPSHOT = 6 + DATABASE_FAILOVER = 7 state: State = proto.Field( proto.ENUM, diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_database_failover_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_execute_airflow_command_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_fetch_database_properties_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_poll_airflow_command_sync.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_async.py diff --git a/owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py b/packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py similarity index 100% rename from owl-bot-staging/google-cloud-orchestration-airflow/v1beta1/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py rename to packages/google-cloud-orchestration-airflow/samples/generated_samples/composer_v1beta1_generated_environments_stop_airflow_command_sync.py 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 5ba2ed3abc15..fe40746345fa 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 @@ -333,6 +333,159 @@ ], "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.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": { @@ -412,7 +565,635 @@ "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_delete_environment_async.py" + "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.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.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, @@ -421,22 +1202,22 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", "shortName": "EnvironmentsClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.delete_environment", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_environments", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.DeleteEnvironment", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListEnvironments", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "DeleteEnvironment" + "shortName": "ListEnvironments" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.DeleteEnvironmentRequest" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -452,22 +1233,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_environment" + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsPager", + "shortName": "list_environments" }, - "description": "Sample for DeleteEnvironment", - "file": "composer_v1beta1_generated_environments_delete_environment_sync.py", + "description": "Sample for ListEnvironments", + "file": "composer_v1beta1_generated_environments_list_environments_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_DeleteEnvironment_sync", + "regionTag": "composer_v1beta1_generated_Environments_ListEnvironments_sync", "segments": [ { - "end": 54, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 51, "start": 27, "type": "SHORT" }, @@ -482,17 +1263,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 51, + "end": 47, "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 52, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_delete_environment_sync.py" + "title": "composer_v1beta1_generated_environments_list_environments_sync.py" }, { "canonical": true, @@ -502,23 +1283,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", "shortName": "EnvironmentsAsyncClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.get_environment", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.load_snapshot", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetEnvironment", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "GetEnvironment" + "shortName": "LoadSnapshot" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" }, { "name": "retry", @@ -533,22 +1310,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment", - "shortName": "get_environment" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "load_snapshot" }, - "description": "Sample for GetEnvironment", - "file": "composer_v1beta1_generated_environments_get_environment_async.py", + "description": "Sample for LoadSnapshot", + "file": "composer_v1beta1_generated_environments_load_snapshot_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetEnvironment_async", + "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_async", "segments": [ { - "end": 50, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 54, "start": 27, "type": "SHORT" }, @@ -563,17 +1340,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 47, + "end": 51, "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_get_environment_async.py" + "title": "composer_v1beta1_generated_environments_load_snapshot_async.py" }, { "canonical": true, @@ -582,23 +1359,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", "shortName": "EnvironmentsClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.get_environment", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.load_snapshot", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.GetEnvironment", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "GetEnvironment" + "shortName": "LoadSnapshot" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.GetEnvironmentRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" }, { "name": "retry", @@ -613,22 +1386,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.Environment", - "shortName": "get_environment" + "resultType": "google.api_core.operation.Operation", + "shortName": "load_snapshot" }, - "description": "Sample for GetEnvironment", - "file": "composer_v1beta1_generated_environments_get_environment_sync.py", + "description": "Sample for LoadSnapshot", + "file": "composer_v1beta1_generated_environments_load_snapshot_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_GetEnvironment_sync", + "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_sync", "segments": [ { - "end": 50, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 54, "start": 27, "type": "SHORT" }, @@ -643,17 +1416,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 47, + "end": 51, "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_get_environment_sync.py" + "title": "composer_v1beta1_generated_environments_load_snapshot_sync.py" }, { "canonical": true, @@ -663,23 +1436,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", "shortName": "EnvironmentsAsyncClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.list_environments", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.poll_airflow_command", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListEnvironments", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.PollAirflowCommand", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "ListEnvironments" + "shortName": "PollAirflowCommand" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest" }, { "name": "retry", @@ -694,22 +1463,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsAsyncPager", - "shortName": "list_environments" + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse", + "shortName": "poll_airflow_command" }, - "description": "Sample for ListEnvironments", - "file": "composer_v1beta1_generated_environments_list_environments_async.py", + "description": "Sample for PollAirflowCommand", + "file": "composer_v1beta1_generated_environments_poll_airflow_command_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListEnvironments_async", + "regionTag": "composer_v1beta1_generated_Environments_PollAirflowCommand_async", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -729,12 +1498,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 51, "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_list_environments_async.py" + "title": "composer_v1beta1_generated_environments_poll_airflow_command_async.py" }, { "canonical": true, @@ -743,23 +1512,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", "shortName": "EnvironmentsClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.list_environments", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.poll_airflow_command", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.ListEnvironments", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.PollAirflowCommand", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "ListEnvironments" + "shortName": "PollAirflowCommand" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.ListEnvironmentsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandRequest" }, { "name": "retry", @@ -774,22 +1539,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.orchestration.airflow.service_v1beta1.services.environments.pagers.ListEnvironmentsPager", - "shortName": "list_environments" + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.PollAirflowCommandResponse", + "shortName": "poll_airflow_command" }, - "description": "Sample for ListEnvironments", - "file": "composer_v1beta1_generated_environments_list_environments_sync.py", + "description": "Sample for PollAirflowCommand", + "file": "composer_v1beta1_generated_environments_poll_airflow_command_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_ListEnvironments_sync", + "regionTag": "composer_v1beta1_generated_Environments_PollAirflowCommand_sync", "segments": [ { - "end": 51, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 50, "start": 27, "type": "SHORT" }, @@ -809,12 +1574,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 51, "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_list_environments_sync.py" + "title": "composer_v1beta1_generated_environments_poll_airflow_command_sync.py" }, { "canonical": true, @@ -824,19 +1589,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", "shortName": "EnvironmentsAsyncClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.load_snapshot", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.restart_web_server", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "LoadSnapshot" + "shortName": "RestartWebServer" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" }, { "name": "retry", @@ -852,13 +1617,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "load_snapshot" + "shortName": "restart_web_server" }, - "description": "Sample for LoadSnapshot", - "file": "composer_v1beta1_generated_environments_load_snapshot_async.py", + "description": "Sample for RestartWebServer", + "file": "composer_v1beta1_generated_environments_restart_web_server_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_async", + "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_async", "segments": [ { "end": 54, @@ -891,7 +1656,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_load_snapshot_async.py" + "title": "composer_v1beta1_generated_environments_restart_web_server_async.py" }, { "canonical": true, @@ -900,19 +1665,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", "shortName": "EnvironmentsClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.load_snapshot", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.restart_web_server", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.LoadSnapshot", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "LoadSnapshot" + "shortName": "RestartWebServer" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.LoadSnapshotRequest" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" }, { "name": "retry", @@ -928,13 +1693,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "load_snapshot" + "shortName": "restart_web_server" }, - "description": "Sample for LoadSnapshot", - "file": "composer_v1beta1_generated_environments_load_snapshot_sync.py", + "description": "Sample for RestartWebServer", + "file": "composer_v1beta1_generated_environments_restart_web_server_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_LoadSnapshot_sync", + "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_sync", "segments": [ { "end": 54, @@ -967,7 +1732,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_load_snapshot_sync.py" + "title": "composer_v1beta1_generated_environments_restart_web_server_sync.py" }, { "canonical": true, @@ -977,19 +1742,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", "shortName": "EnvironmentsAsyncClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.restart_web_server", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.save_snapshot", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "RestartWebServer" + "shortName": "SaveSnapshot" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" }, { "name": "retry", @@ -1005,13 +1770,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "restart_web_server" + "shortName": "save_snapshot" }, - "description": "Sample for RestartWebServer", - "file": "composer_v1beta1_generated_environments_restart_web_server_async.py", + "description": "Sample for SaveSnapshot", + "file": "composer_v1beta1_generated_environments_save_snapshot_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_async", + "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_async", "segments": [ { "end": 54, @@ -1044,7 +1809,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_restart_web_server_async.py" + "title": "composer_v1beta1_generated_environments_save_snapshot_async.py" }, { "canonical": true, @@ -1053,19 +1818,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", "shortName": "EnvironmentsClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.restart_web_server", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.save_snapshot", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.RestartWebServer", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "RestartWebServer" + "shortName": "SaveSnapshot" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.RestartWebServerRequest" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" }, { "name": "retry", @@ -1081,13 +1846,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "restart_web_server" + "shortName": "save_snapshot" }, - "description": "Sample for RestartWebServer", - "file": "composer_v1beta1_generated_environments_restart_web_server_sync.py", + "description": "Sample for SaveSnapshot", + "file": "composer_v1beta1_generated_environments_save_snapshot_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_RestartWebServer_sync", + "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_sync", "segments": [ { "end": 54, @@ -1120,7 +1885,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_restart_web_server_sync.py" + "title": "composer_v1beta1_generated_environments_save_snapshot_sync.py" }, { "canonical": true, @@ -1130,19 +1895,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient", "shortName": "EnvironmentsAsyncClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.save_snapshot", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsAsyncClient.stop_airflow_command", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.StopAirflowCommand", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "SaveSnapshot" + "shortName": "StopAirflowCommand" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest" }, { "name": "retry", @@ -1157,22 +1922,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "save_snapshot" + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse", + "shortName": "stop_airflow_command" }, - "description": "Sample for SaveSnapshot", - "file": "composer_v1beta1_generated_environments_save_snapshot_async.py", + "description": "Sample for StopAirflowCommand", + "file": "composer_v1beta1_generated_environments_stop_airflow_command_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_async", + "regionTag": "composer_v1beta1_generated_Environments_StopAirflowCommand_async", "segments": [ { - "end": 54, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 50, "start": 27, "type": "SHORT" }, @@ -1187,17 +1952,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 51, + "end": 47, "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_save_snapshot_async.py" + "title": "composer_v1beta1_generated_environments_stop_airflow_command_async.py" }, { "canonical": true, @@ -1206,19 +1971,19 @@ "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient", "shortName": "EnvironmentsClient" }, - "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.save_snapshot", + "fullName": "google.cloud.orchestration.airflow.service_v1beta1.EnvironmentsClient.stop_airflow_command", "method": { - "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.SaveSnapshot", + "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments.StopAirflowCommand", "service": { "fullName": "google.cloud.orchestration.airflow.service.v1beta1.Environments", "shortName": "Environments" }, - "shortName": "SaveSnapshot" + "shortName": "StopAirflowCommand" }, "parameters": [ { "name": "request", - "type": "google.cloud.orchestration.airflow.service_v1beta1.types.SaveSnapshotRequest" + "type": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandRequest" }, { "name": "retry", @@ -1233,22 +1998,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "save_snapshot" + "resultType": "google.cloud.orchestration.airflow.service_v1beta1.types.StopAirflowCommandResponse", + "shortName": "stop_airflow_command" }, - "description": "Sample for SaveSnapshot", - "file": "composer_v1beta1_generated_environments_save_snapshot_sync.py", + "description": "Sample for StopAirflowCommand", + "file": "composer_v1beta1_generated_environments_stop_airflow_command_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "composer_v1beta1_generated_Environments_SaveSnapshot_sync", + "regionTag": "composer_v1beta1_generated_Environments_StopAirflowCommand_sync", "segments": [ { - "end": 54, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 50, "start": 27, "type": "SHORT" }, @@ -1263,17 +2028,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 51, + "end": 47, "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "composer_v1beta1_generated_environments_save_snapshot_sync.py" + "title": "composer_v1beta1_generated_environments_stop_airflow_command_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1beta1_keywords.py b/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1beta1_keywords.py index a4ae0cb0021e..ec51364c3cad 100644 --- a/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1beta1_keywords.py +++ b/packages/google-cloud-orchestration-airflow/scripts/fixup_service_v1beta1_keywords.py @@ -41,13 +41,18 @@ class serviceCallTransformer(cst.CSTTransformer): METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'check_upgrade': ('environment', 'image_version', ), 'create_environment': ('parent', 'environment', ), + 'database_failover': ('environment', ), 'delete_environment': ('name', ), + 'execute_airflow_command': ('environment', 'command', 'subcommand', 'parameters', ), + 'fetch_database_properties': ('environment', ), 'get_environment': ('name', ), 'list_environments': ('parent', 'page_size', 'page_token', ), 'list_image_versions': ('parent', 'page_size', 'page_token', 'include_past_releases', ), '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', ), } 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 1d04aeb1d1e0..2e0991985c5d 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 @@ -2438,11 +2438,11 @@ async def test_check_upgrade_field_headers_async(): @pytest.mark.parametrize( "request_type", [ - environments.SaveSnapshotRequest, + environments.ExecuteAirflowCommandRequest, dict, ], ) -def test_save_snapshot(request_type, transport: str = "grpc"): +def test_execute_airflow_command(request_type, transport: str = "grpc"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2453,21 +2453,32 @@ def test_save_snapshot(request_type, transport: str = "grpc"): 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: + with mock.patch.object( + type(client.transport.execute_airflow_command), "__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) + 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] - assert args[0] == environments.SaveSnapshotRequest() + assert args[0] == environments.ExecuteAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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_save_snapshot_empty_call(): +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( @@ -2476,16 +2487,19 @@ def test_save_snapshot_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.save_snapshot), "__call__") as call: - client.save_snapshot() + with mock.patch.object( + type(client.transport.execute_airflow_command), "__call__" + ) as call: + client.execute_airflow_command() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environments.SaveSnapshotRequest() + assert args[0] == environments.ExecuteAirflowCommandRequest() @pytest.mark.asyncio -async def test_save_snapshot_async( - transport: str = "grpc_asyncio", request_type=environments.SaveSnapshotRequest +async def test_execute_airflow_command_async( + transport: str = "grpc_asyncio", + request_type=environments.ExecuteAirflowCommandRequest, ): client = EnvironmentsAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2497,42 +2511,55 @@ async def test_save_snapshot_async( 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: + 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( - operations_pb2.Operation(name="operations/spam") + environments.ExecuteAirflowCommandResponse( + execution_id="execution_id_value", + pod="pod_value", + pod_namespace="pod_namespace_value", + error="error_value", + ) ) - response = await client.save_snapshot(request) + 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] - assert args[0] == environments.SaveSnapshotRequest() + assert args[0] == environments.ExecuteAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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_save_snapshot_async_from_dict(): - await test_save_snapshot_async(request_type=dict) +async def test_execute_airflow_command_async_from_dict(): + await test_execute_airflow_command_async(request_type=dict) -def test_save_snapshot_field_headers(): +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.SaveSnapshotRequest() + 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.save_snapshot), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.save_snapshot(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 @@ -2548,23 +2575,25 @@ def test_save_snapshot_field_headers(): @pytest.mark.asyncio -async def test_save_snapshot_field_headers_async(): +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.SaveSnapshotRequest() + 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.save_snapshot), "__call__") as call: + with mock.patch.object( + type(client.transport.execute_airflow_command), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + environments.ExecuteAirflowCommandResponse() ) - await client.save_snapshot(request) + await client.execute_airflow_command(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2582,11 +2611,11 @@ async def test_save_snapshot_field_headers_async(): @pytest.mark.parametrize( "request_type", [ - environments.LoadSnapshotRequest, + environments.StopAirflowCommandRequest, dict, ], ) -def test_load_snapshot(request_type, transport: str = "grpc"): +def test_stop_airflow_command(request_type, transport: str = "grpc"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2597,21 +2626,28 @@ def test_load_snapshot(request_type, transport: str = "grpc"): 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: + with mock.patch.object( + type(client.transport.stop_airflow_command), "__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) + 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] - assert args[0] == environments.LoadSnapshotRequest() + assert args[0] == environments.StopAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ["output_value"] -def test_load_snapshot_empty_call(): +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( @@ -2620,16 +2656,18 @@ def test_load_snapshot_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.load_snapshot), "__call__") as call: - client.load_snapshot() + with mock.patch.object( + type(client.transport.stop_airflow_command), "__call__" + ) as call: + client.stop_airflow_command() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == environments.LoadSnapshotRequest() + assert args[0] == environments.StopAirflowCommandRequest() @pytest.mark.asyncio -async def test_load_snapshot_async( - transport: str = "grpc_asyncio", request_type=environments.LoadSnapshotRequest +async def test_stop_airflow_command_async( + transport: str = "grpc_asyncio", request_type=environments.StopAirflowCommandRequest ): client = EnvironmentsAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2641,42 +2679,51 @@ async def test_load_snapshot_async( 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: + 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( - operations_pb2.Operation(name="operations/spam") + environments.StopAirflowCommandResponse( + is_done=True, + output=["output_value"], + ) ) - response = await client.load_snapshot(request) + 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] - assert args[0] == environments.LoadSnapshotRequest() + assert args[0] == environments.StopAirflowCommandRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, environments.StopAirflowCommandResponse) + assert response.is_done is True + assert response.output == ["output_value"] @pytest.mark.asyncio -async def test_load_snapshot_async_from_dict(): - await test_load_snapshot_async(request_type=dict) +async def test_stop_airflow_command_async_from_dict(): + await test_stop_airflow_command_async(request_type=dict) -def test_load_snapshot_field_headers(): +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.LoadSnapshotRequest() + 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.load_snapshot), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.load_snapshot(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 @@ -2692,23 +2739,25 @@ def test_load_snapshot_field_headers(): @pytest.mark.asyncio -async def test_load_snapshot_field_headers_async(): +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.LoadSnapshotRequest() + 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.load_snapshot), "__call__") as call: + with mock.patch.object( + type(client.transport.stop_airflow_command), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + environments.StopAirflowCommandResponse() ) - await client.load_snapshot(request) + await client.stop_airflow_command(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2726,185 +2775,1863 @@ async def test_load_snapshot_field_headers_async(): @pytest.mark.parametrize( "request_type", [ - environments.CreateEnvironmentRequest, + environments.PollAirflowCommandRequest, dict, ], ) -def test_create_environment_rest(request_type): +def test_poll_airflow_command(request_type, transport: str = "grpc"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # 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}, - }, - "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, - }, - "private_environment_config": { - "enable_private_environment": 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"}, - "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}, - }, - "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", - } - }, - }, - "uuid": "uuid_value", - "state": 1, - "create_time": {}, - "update_time": {}, - "labels": {}, - } - request = request_type(**request_init) - - # Mock the http request call within the method and 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") + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_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: + # Designate an appropriate return value for the call. + call.return_value = environments.PollAirflowCommandResponse( + output_end=True, + ) + response = client.poll_airflow_command(request) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - 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] + assert args[0] == environments.PollAirflowCommandRequest() # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_environment_rest_interceptors(null_interceptor): - transport = transports.EnvironmentsRestTransport( +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(), - interceptor=None - if null_interceptor - else transports.EnvironmentsRestInterceptor(), + transport="grpc", ) - 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() + # 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: + 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( + 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] + assert args[0] == environments.PollAirflowCommandRequest() + + # 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.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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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: + 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( + 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] + assert args[0] == environments.SaveSnapshotRequest() + + # 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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: + 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( + 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] + assert args[0] == environments.LoadSnapshotRequest() + + # 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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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: + 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( + 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] + assert args[0] == environments.DatabaseFailoverRequest() + + # 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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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: + 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( + 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] + assert args[0] == environments.FetchDatabasePropertiesRequest() + + # 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}, + }, + "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, + }, + "private_environment_config": { + "enable_private_environment": 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"}, + "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}, + }, + "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", + } + }, + "resilience_mode": 1, + }, + "uuid": "uuid_value", + "state": 1, + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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_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}, + }, + "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, + }, + "private_environment_config": { + "enable_private_environment": 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"}, + "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}, + }, + "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", + } + }, + "resilience_mode": 1, + }, + "uuid": "uuid_value", + "state": 1, + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest 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, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + + +@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 + pb_return_value = environments.Environment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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" + + +@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 + pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_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}, + }, + "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, + }, + "private_environment_config": { + "enable_private_environment": 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"}, + "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}, + }, + "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", + } + }, + "resilience_mode": 1, + }, + "uuid": "uuid_value", + "state": 1, + "create_time": {}, + "update_time": {}, + "labels": {}, + } + request = request_type(**request_init) + + # Mock the http request call within the method and 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_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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_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.CreateEnvironmentRequest() + request = environments.UpdateEnvironmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -2912,7 +4639,7 @@ def test_create_environment_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_environment( + client.update_environment( request, metadata=[ ("key", "val"), @@ -2924,8 +4651,8 @@ def test_create_environment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_environment_rest_bad_request( - transport: str = "rest", request_type=environments.CreateEnvironmentRequest +def test_update_environment_rest_bad_request( + transport: str = "rest", request_type=environments.UpdateEnvironmentRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2933,7 +4660,7 @@ def test_create_environment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/environments/sample3"} request_init["environment"] = { "name": "name_value", "config": { @@ -3034,6 +4761,7 @@ def test_create_environment_rest_bad_request( "time_zone": "time_zone_value", } }, + "resilience_mode": 1, }, "uuid": "uuid_value", "state": 1, @@ -3052,10 +4780,10 @@ def test_create_environment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_environment(request) + client.update_environment(request) -def test_create_environment_rest_flattened(): +def test_update_environment_rest_flattened(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3066,193 +4794,6 @@ def test_create_environment_rest_flattened(): # 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, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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 - - -@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" @@ -3261,18 +4802,19 @@ def test_get_environment_rest_flattened(): # 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 - pb_return_value = environments.Environment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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) + client.update_environment(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -3285,7 +4827,7 @@ def test_get_environment_rest_flattened(): ) -def test_get_environment_rest_flattened_error(transport: str = "rest"): +def test_update_environment_rest_flattened_error(transport: str = "rest"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3294,13 +4836,15 @@ def test_get_environment_rest_flattened_error(transport: str = "rest"): # 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(), + 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_get_environment_rest_error(): +def test_update_environment_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -3309,44 +4853,40 @@ def test_get_environment_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.ListEnvironmentsRequest, + environments.DeleteEnvironmentRequest, dict, ], ) -def test_list_environments_rest(request_type): +def test_delete_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 = {"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.ListEnvironmentsResponse( - next_page_token="next_page_token_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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) + response = client.delete_environment(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" + assert response.operation.name == "operations/spam" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_environments_rest_interceptors(null_interceptor): +def test_delete_environment_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3359,14 +4899,16 @@ def test_list_environments_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_list_environments" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EnvironmentsRestInterceptor, "post_delete_environment" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_list_environments" + transports.EnvironmentsRestInterceptor, "pre_delete_environment" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.ListEnvironmentsRequest.pb( - environments.ListEnvironmentsRequest() + pb_message = environments.DeleteEnvironmentRequest.pb( + environments.DeleteEnvironmentRequest() ) transcode.return_value = { "method": "post", @@ -3378,19 +4920,19 @@ def test_list_environments_rest_interceptors(null_interceptor): 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() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = environments.ListEnvironmentsRequest() + request = environments.DeleteEnvironmentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = environments.ListEnvironmentsResponse() + post.return_value = operations_pb2.Operation() - client.list_environments( + client.delete_environment( request, metadata=[ ("key", "val"), @@ -3402,8 +4944,8 @@ def test_list_environments_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_environments_rest_bad_request( - transport: str = "rest", request_type=environments.ListEnvironmentsRequest +def test_delete_environment_rest_bad_request( + transport: str = "rest", request_type=environments.DeleteEnvironmentRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3411,7 +4953,7 @@ def test_list_environments_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + 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. @@ -3423,10 +4965,10 @@ def test_list_environments_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_environments(request) + client.delete_environment(request) -def test_list_environments_rest_flattened(): +def test_delete_environment_rest_flattened(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3435,39 +4977,40 @@ def test_list_environments_rest_flattened(): # Mock the http request call within the method and 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() + 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"} + sample_request = { + "name": "projects/sample1/locations/sample2/environments/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = environments.ListEnvironmentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_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) + 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/{parent=projects/*/locations/*}/environments" + "%s/v1beta1/{name=projects/*/locations/*/environments/*}" % client.transport._host, args[1], ) -def test_list_environments_rest_flattened_error(transport: str = "rest"): +def test_delete_environment_rest_flattened_error(transport: str = "rest"): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3476,83 +5019,26 @@ def test_list_environments_rest_flattened_error(transport: str = "rest"): # 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", + client.delete_environment( + environments.DeleteEnvironmentRequest(), + name="name_value", ) -def test_list_environments_rest_pager(transport: str = "rest"): +def test_delete_environment_rest_error(): client = EnvironmentsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # 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, + environments.RestartWebServerRequest, dict, ], ) -def test_update_environment_rest(request_type): +def test_restart_web_server_rest(request_type): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3560,112 +5046,131 @@ def test_update_environment_rest(request_type): # 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}, - }, - "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, - }, - "private_environment_config": { - "enable_private_environment": 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"}, - "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}, - }, - "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", - } - }, - }, - "uuid": "uuid_value", - "state": 1, - "create_time": {}, - "update_time": {}, - "labels": {}, + request = request_type(**request_init) + + # Mock the http request call within the method and 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" + + +@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) @@ -3681,96 +5186,152 @@ def test_update_environment_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_environment(request) + response = client.check_upgrade(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -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, - including_default_value_fields=False, - use_integers_for_enums=False, - ) +@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, + } - # verify fields with default values are dropped + 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() + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_environment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + request = environments.CheckUpgradeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() - # verify required fields with default values are now present + client.check_upgrade( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - 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) + pre.assert_called_once() + post.assert_called_once() - # verify required fields with non-default values are left alone +def test_check_upgrade_rest_bad_request( + transport: str = "rest", request_type=environments.CheckUpgradeRequest +): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) + + # send a request that will satisfy transcoding + request_init = { + "environment": "projects/sample1/locations/sample2/environments/sample3" + } 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 + # Mock the http request call within the method and fake a BadRequest 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) - 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 +def test_check_upgrade_rest_error(): + client = EnvironmentsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - response = client.update_environment(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params +@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", + ) -def test_update_environment_rest_unset_required_fields(): - transport = transports.EnvironmentsRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = environments.ExecuteAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.execute_airflow_command(request) - unset_fields = transport.update_environment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask",)) & set(("updateMask",))) + # Establish that the response is the type that we expect. + assert isinstance(response, environments.ExecuteAirflowCommandResponse) + assert response.execution_id == "execution_id_value" + assert response.pod == "pod_value" + assert response.pod_namespace == "pod_namespace_value" + assert response.error == "error_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_environment_rest_interceptors(null_interceptor): +def test_execute_airflow_command_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -3783,16 +5344,14 @@ def test_update_environment_rest_interceptors(null_interceptor): ) 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" + transports.EnvironmentsRestInterceptor, "post_execute_airflow_command" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_update_environment" + transports.EnvironmentsRestInterceptor, "pre_execute_airflow_command" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.UpdateEnvironmentRequest.pb( - environments.UpdateEnvironmentRequest() + pb_message = environments.ExecuteAirflowCommandRequest.pb( + environments.ExecuteAirflowCommandRequest() ) transcode.return_value = { "method": "post", @@ -3804,19 +5363,19 @@ def test_update_environment_rest_interceptors(null_interceptor): 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() + req.return_value._content = environments.ExecuteAirflowCommandResponse.to_json( + environments.ExecuteAirflowCommandResponse() ) - request = environments.UpdateEnvironmentRequest() + request = environments.ExecuteAirflowCommandRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = environments.ExecuteAirflowCommandResponse() - client.update_environment( + client.execute_airflow_command( request, metadata=[ ("key", "val"), @@ -3828,8 +5387,8 @@ def test_update_environment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_environment_rest_bad_request( - transport: str = "rest", request_type=environments.UpdateEnvironmentRequest +def test_execute_airflow_command_rest_bad_request( + transport: str = "rest", request_type=environments.ExecuteAirflowCommandRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3837,113 +5396,8 @@ def test_update_environment_rest_bad_request( ) # 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}, - }, - "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, - }, - "private_environment_config": { - "enable_private_environment": 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"}, - "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}, - }, - "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", - } - }, - }, - "uuid": "uuid_value", - "state": 1, - "create_time": {}, - "update_time": {}, - "labels": {}, + request_init = { + "environment": "projects/sample1/locations/sample2/environments/sample3" } request = request_type(**request_init) @@ -3956,71 +5410,142 @@ def test_update_environment_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_environment(request) + client.execute_airflow_command(request) -def test_update_environment_rest_flattened(): +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 = 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"]), + return_value = environments.StopAirflowCommandResponse( + is_done=True, + output=["output_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) + pb_return_value = environments.StopAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value + response = client.stop_airflow_command(request) - client.update_environment(**mock_args) + # 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"] - # 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], + +@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() -def test_update_environment_rest_flattened_error(transport: str = "rest"): + 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, ) - # 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"]), - ) + # 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_update_environment_rest_error(): +def test_stop_airflow_command_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4029,40 +5554,46 @@ def test_update_environment_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.DeleteEnvironmentRequest, + environments.PollAirflowCommandRequest, dict, ], ) -def test_delete_environment_rest(request_type): +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 = {"name": "projects/sample1/locations/sample2/environments/sample3"} + 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") + return_value = environments.PollAirflowCommandResponse( + output_end=True, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = environments.PollAirflowCommandResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_environment(request) + response = client.poll_airflow_command(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, environments.PollAirflowCommandResponse) + assert response.output_end is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_environment_rest_interceptors(null_interceptor): +def test_poll_airflow_command_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -4075,16 +5606,14 @@ def test_delete_environment_rest_interceptors(null_interceptor): ) 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" + transports.EnvironmentsRestInterceptor, "post_poll_airflow_command" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_delete_environment" + transports.EnvironmentsRestInterceptor, "pre_poll_airflow_command" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.DeleteEnvironmentRequest.pb( - environments.DeleteEnvironmentRequest() + pb_message = environments.PollAirflowCommandRequest.pb( + environments.PollAirflowCommandRequest() ) transcode.return_value = { "method": "post", @@ -4096,19 +5625,19 @@ def test_delete_environment_rest_interceptors(null_interceptor): 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() + req.return_value._content = environments.PollAirflowCommandResponse.to_json( + environments.PollAirflowCommandResponse() ) - request = environments.DeleteEnvironmentRequest() + request = environments.PollAirflowCommandRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = environments.PollAirflowCommandResponse() - client.delete_environment( + client.poll_airflow_command( request, metadata=[ ("key", "val"), @@ -4120,8 +5649,8 @@ def test_delete_environment_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_environment_rest_bad_request( - transport: str = "rest", request_type=environments.DeleteEnvironmentRequest +def test_poll_airflow_command_rest_bad_request( + transport: str = "rest", request_type=environments.PollAirflowCommandRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4129,7 +5658,9 @@ def test_delete_environment_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/environments/sample3"} + 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. @@ -4141,67 +5672,10 @@ def test_delete_environment_rest_bad_request( 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", - ) + client.poll_airflow_command(request) -def test_delete_environment_rest_error(): +def test_poll_airflow_command_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4210,18 +5684,20 @@ def test_delete_environment_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.RestartWebServerRequest, + environments.SaveSnapshotRequest, dict, ], ) -def test_restart_web_server_rest(request_type): +def test_save_snapshot_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": "projects/sample1/locations/sample2/environments/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -4236,14 +5712,14 @@ def test_restart_web_server_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restart_web_server(request) + response = client.save_snapshot(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restart_web_server_rest_interceptors(null_interceptor): +def test_save_snapshot_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -4258,14 +5734,14 @@ def test_restart_web_server_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_restart_web_server" + transports.EnvironmentsRestInterceptor, "post_save_snapshot" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_restart_web_server" + transports.EnvironmentsRestInterceptor, "pre_save_snapshot" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.RestartWebServerRequest.pb( - environments.RestartWebServerRequest() + pb_message = environments.SaveSnapshotRequest.pb( + environments.SaveSnapshotRequest() ) transcode.return_value = { "method": "post", @@ -4281,7 +5757,7 @@ def test_restart_web_server_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = environments.RestartWebServerRequest() + request = environments.SaveSnapshotRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -4289,7 +5765,7 @@ def test_restart_web_server_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.restart_web_server( + client.save_snapshot( request, metadata=[ ("key", "val"), @@ -4301,8 +5777,8 @@ def test_restart_web_server_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restart_web_server_rest_bad_request( - transport: str = "rest", request_type=environments.RestartWebServerRequest +def test_save_snapshot_rest_bad_request( + transport: str = "rest", request_type=environments.SaveSnapshotRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4310,7 +5786,9 @@ def test_restart_web_server_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/environments/sample3"} + 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. @@ -4322,10 +5800,10 @@ def test_restart_web_server_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.restart_web_server(request) + client.save_snapshot(request) -def test_restart_web_server_rest_error(): +def test_save_snapshot_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4334,11 +5812,11 @@ def test_restart_web_server_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.CheckUpgradeRequest, + environments.LoadSnapshotRequest, dict, ], ) -def test_check_upgrade_rest(request_type): +def test_load_snapshot_rest(request_type): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4362,14 +5840,14 @@ def test_check_upgrade_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.check_upgrade(request) + response = client.load_snapshot(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_check_upgrade_rest_interceptors(null_interceptor): +def test_load_snapshot_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -4384,14 +5862,14 @@ def test_check_upgrade_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_check_upgrade" + transports.EnvironmentsRestInterceptor, "post_load_snapshot" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_check_upgrade" + transports.EnvironmentsRestInterceptor, "pre_load_snapshot" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.CheckUpgradeRequest.pb( - environments.CheckUpgradeRequest() + pb_message = environments.LoadSnapshotRequest.pb( + environments.LoadSnapshotRequest() ) transcode.return_value = { "method": "post", @@ -4407,7 +5885,7 @@ def test_check_upgrade_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = environments.CheckUpgradeRequest() + request = environments.LoadSnapshotRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -4415,7 +5893,7 @@ def test_check_upgrade_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.check_upgrade( + client.load_snapshot( request, metadata=[ ("key", "val"), @@ -4427,8 +5905,8 @@ def test_check_upgrade_rest_interceptors(null_interceptor): post.assert_called_once() -def test_check_upgrade_rest_bad_request( - transport: str = "rest", request_type=environments.CheckUpgradeRequest +def test_load_snapshot_rest_bad_request( + transport: str = "rest", request_type=environments.LoadSnapshotRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4450,10 +5928,10 @@ def test_check_upgrade_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.check_upgrade(request) + client.load_snapshot(request) -def test_check_upgrade_rest_error(): +def test_load_snapshot_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4462,11 +5940,11 @@ def test_check_upgrade_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.SaveSnapshotRequest, + environments.DatabaseFailoverRequest, dict, ], ) -def test_save_snapshot_rest(request_type): +def test_database_failover_rest(request_type): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4490,14 +5968,14 @@ def test_save_snapshot_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.save_snapshot(request) + response = client.database_failover(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_save_snapshot_rest_interceptors(null_interceptor): +def test_database_failover_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -4512,14 +5990,14 @@ def test_save_snapshot_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.EnvironmentsRestInterceptor, "post_save_snapshot" + transports.EnvironmentsRestInterceptor, "post_database_failover" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_save_snapshot" + transports.EnvironmentsRestInterceptor, "pre_database_failover" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.SaveSnapshotRequest.pb( - environments.SaveSnapshotRequest() + pb_message = environments.DatabaseFailoverRequest.pb( + environments.DatabaseFailoverRequest() ) transcode.return_value = { "method": "post", @@ -4535,7 +6013,7 @@ def test_save_snapshot_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = environments.SaveSnapshotRequest() + request = environments.DatabaseFailoverRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -4543,7 +6021,7 @@ def test_save_snapshot_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.save_snapshot( + client.database_failover( request, metadata=[ ("key", "val"), @@ -4555,8 +6033,8 @@ def test_save_snapshot_rest_interceptors(null_interceptor): post.assert_called_once() -def test_save_snapshot_rest_bad_request( - transport: str = "rest", request_type=environments.SaveSnapshotRequest +def test_database_failover_rest_bad_request( + transport: str = "rest", request_type=environments.DatabaseFailoverRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4578,10 +6056,10 @@ def test_save_snapshot_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.save_snapshot(request) + client.database_failover(request) -def test_save_snapshot_rest_error(): +def test_database_failover_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4590,11 +6068,11 @@ def test_save_snapshot_rest_error(): @pytest.mark.parametrize( "request_type", [ - environments.LoadSnapshotRequest, + environments.FetchDatabasePropertiesRequest, dict, ], ) -def test_load_snapshot_rest(request_type): +def test_fetch_database_properties_rest(request_type): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4609,23 +6087,119 @@ def test_load_snapshot_rest(request_type): # Mock the http request call within the method and 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") + 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 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = environments.FetchDatabasePropertiesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.load_snapshot(request) + response = client.fetch_database_properties(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + 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_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, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).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 + + pb_return_value = environments.FetchDatabasePropertiesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_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_load_snapshot_rest_interceptors(null_interceptor): +def test_fetch_database_properties_rest_interceptors(null_interceptor): transport = transports.EnvironmentsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -4638,16 +6212,14 @@ def test_load_snapshot_rest_interceptors(null_interceptor): ) 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" + transports.EnvironmentsRestInterceptor, "post_fetch_database_properties" ) as post, mock.patch.object( - transports.EnvironmentsRestInterceptor, "pre_load_snapshot" + transports.EnvironmentsRestInterceptor, "pre_fetch_database_properties" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = environments.LoadSnapshotRequest.pb( - environments.LoadSnapshotRequest() + pb_message = environments.FetchDatabasePropertiesRequest.pb( + environments.FetchDatabasePropertiesRequest() ) transcode.return_value = { "method": "post", @@ -4659,19 +6231,21 @@ def test_load_snapshot_rest_interceptors(null_interceptor): 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() + req.return_value._content = ( + environments.FetchDatabasePropertiesResponse.to_json( + environments.FetchDatabasePropertiesResponse() + ) ) - request = environments.LoadSnapshotRequest() + request = environments.FetchDatabasePropertiesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = environments.FetchDatabasePropertiesResponse() - client.load_snapshot( + client.fetch_database_properties( request, metadata=[ ("key", "val"), @@ -4683,8 +6257,8 @@ def test_load_snapshot_rest_interceptors(null_interceptor): post.assert_called_once() -def test_load_snapshot_rest_bad_request( - transport: str = "rest", request_type=environments.LoadSnapshotRequest +def test_fetch_database_properties_rest_bad_request( + transport: str = "rest", request_type=environments.FetchDatabasePropertiesRequest ): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4706,10 +6280,10 @@ def test_load_snapshot_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.load_snapshot(request) + client.fetch_database_properties(request) -def test_load_snapshot_rest_error(): +def test_fetch_database_properties_rest_error(): client = EnvironmentsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -4861,8 +6435,13 @@ def test_environments_base_transport(): "delete_environment", "restart_web_server", "check_upgrade", + "execute_airflow_command", + "stop_airflow_command", + "poll_airflow_command", "save_snapshot", "load_snapshot", + "database_failover", + "fetch_database_properties", "get_operation", "delete_operation", "list_operations", @@ -5164,12 +6743,27 @@ def test_environments_client_transport_session_collision(transport_name): 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.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():